I'm trying to post the image with string(mname) to sql/enroll_process.php however the string is echo back successfully onto #response but not work for an image. I am figuring out the way to merge both ajax. I just want to receive the name of the image echoing back onto an alert message or #response.
HTML:
<p id="response"></p>
<form id="enroll_form" method="post" enctype="multipart/form-data">
<input type="text" id="mname" name="mname" >
<input type="file" class="form-control" id="pic" name="pic">
<button type="submit" id="submit_form" >Submit</button>
</form>
Jquery:
$(document).ready(function(){
$('#submit_form').click(function(e){
e.preventDefault(); //prevent page from refresh when click on a button
var mname = $('#mname').val();
var file_data = $('#pic').prop('files')[0];
var form_data = new FormData(); // Create a FormData object
form_data.append('file', file_data); // Append all element in FormData object
if(mname == '' || file_data == '') {
$('#response').html('<span class="text-danger"> All Fields are required</span>');
}
else
{
$.ajax({ //ajax for posting text
url:"sql/enroll_process.php",
method:"POST",
data:$('#enroll_form').serialize(),
beforeSend:function(){
$('#response').html('<span class="text-info"> Loading response...</span>');
},
success:function(data){
$('form').trigger("reset");
$('#response').fadeIn().html(data); //receive echo string
setTimeout(function(){
$('#response').fadeOut("slow");
}, 7000);
}
});
$.ajax({ //ajax for posting image
url: 'sql/enroll_process.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data_g){
alert(data_g); //receive & echo image name as string in alert
}
});
}
});
});
PHP:
<?php
echo $_POST['mname'];
echo $_FILE['pic']['name'];
?>
Solution: Because this question is already answer I cannot post this answer again. I find out the solution. Which send both text and image combined.
$(document).on('click','#submit_form',function (event) {
event.preventDefault();
var form = $('#enroll_form')[0];
var formData = new FormData(form);
$.ajax({
url: "sql/enroll_process.php",
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
$('form').trigger("reset");
$('#response').fadeIn().html(data);
setTimeout(function(){
$('#response').fadeOut("slow");
}, 7000);
}
});
});