I want to submit my image via jquery and ajax , this is my code:
<form name="photo" id="imageUploadForm" enctype="multipart/form-data" action="<?php echo $base_url ?>admin/resid.php" method="post">
<input type="file" accept="image/*" id="imguploadresid" />
</form>
<Script>
$("#imguploadresid").on("change", function() {
$("#imageUploadForm").submit();
});
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault();
var form = $('#imageUploadForm')[0];
var formData = new FormData(form);
$.ajax({
type:'POST',
url: "<?php echo $base_url ?>admin/resid.php",
data:formData,
cache:false,
enctype: 'multipart/form-data',
contentType: false,
processData: false,
success:function(data){
console.log("succes")
},
error: function(data){
console.log("error");
}
});
}));
just to add some explanation , when the use choose an image , the form submits immediately .
it works fine and post the data to my php page , but it's empty and has no data
I put print_R($_POST) in my page and the result is
Array
( )
I logged the ajax post and there was no data posting .
what is the problem ?
$_POST, take a look at$_FILESinstead. And you also need to addnameattribute to the file input, otherwise it's not send to the server. After adding the name, you can access the file using$_FILES["input_name"]["tmp_name"].submitmethod is used inchangehandler, it will just ignore the attached submit handler of the form, and the form is submitted instead of the AJAX call being executed. With jQuerysubmitmethod this works fine.