I have a form where I need to send name of the user along with his profile image. So I have created the form below using HTML & Bootstrap -
<form action="" method="post" id="demoForm" enctype="multipart/form-data">
<div class="form-group">
<label for="">Upload file</label>
<input type="file" name="file" id="file" class="form-control">
</div>
<div class="form-group">
<label for="">Your Name</label>
<input type="text" name="name" id="name" class="form-control">
</div>
<div class="form-group">
<input type="submit" name="save" id="save" value="Save" class="form-control btn btn-success">
</div>
</form>
<div id="result"></div>
Now I need to send this data to my server using PHP. So I have written the following Ajax code using jQuery -
$(document).ready(function(){
$('#demoForm').submit(function(e){
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: "ajax.php",
type: "POST",
data: formData,
contentType : false,
processData: false,
success: function(data){
$('#result').html(data);
}
});
});
});
Now I have written the following PHP code in ajax.php file -
if(isset($_POST['save'])){
$name = $_POST['name'];
$file = $_FILES['file']['name'];
if(!empty($file) && !empty($name)){
$fileName = $_FILES['file']['name'];
$tmp = $_FILES['file']['tmp_name'];
$upload = move_uploaded_file($tmp,'uploads/'.$fileName);
if($upload){
echo "<h2>".$name.", your file has been uploaded successfully!</h2>";
}else{
echo "<h2>Something went wrong!</h2>";
}
}else{echo "File cannot be empty.";}
}else{echo "There is a problem";}
Now, the issue is that I don't get any response from the php file. In other words, the ajax.php file is not receving the data sent through Ajax from the index.php file. Can anyone please help me by pointing out what mistakes I have done? Also share if any solution is there with you. Thanks.
if(isset($_POST['save'])){is the problem.The submit button will only be a successful control if it is used to submit the form.
Your JavaScript is cancelling the submission of the form and making a request using a
FormDataobject instead.Test for the existence of some other piece of data, make
savea hidden input, or remove the check entirely.You have three
ifstatements in your PHP. Only one of them has anelseto output an error. Addingelsewith messages to the other two would make it easier for you to debug your code.