I want to submit my image via jquery and ajax , this is my code:
JavaScript
x
33
33
1
<form name="photo" id="imageUploadForm" enctype="multipart/form-data" action="<?php echo $base_url ?>admin/resid.php" method="post">
2
<input type="file" accept="image/*" id="imguploadresid" />
3
</form>
4
5
<Script>
6
7
$("#imguploadresid").on("change", function() {
8
$("#imageUploadForm").submit();
9
});
10
11
$('#imageUploadForm').on('submit',(function(e) {
12
e.preventDefault();
13
14
var form = $('#imageUploadForm')[0];
15
var formData = new FormData(form);
16
17
$.ajax({
18
type:'POST',
19
url: "<?php echo $base_url ?>admin/resid.php",
20
data:formData,
21
cache:false,
22
enctype: 'multipart/form-data',
23
contentType: false,
24
processData: false,
25
success:function(data){
26
console.log("succes")
27
},
28
error: function(data){
29
console.log("error");
30
}
31
});
32
}));
33
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
JavaScript
1
2
1
Array
2
( )
I logged the ajax post and there was no data posting .
what is the problem ?
Advertisement
Answer
Your image is probably in PHP array $_FILES. You must download your file from it to get your image.
JavaScript
1
2
1
$yourImage = file_get_contents($_FILES['image']['tmp_name']);
2
You have also to add “name” attribute to your input:
JavaScript
1
4
1
<form name="photo" id="imageUploadForm" enctype="multipart/form-data" action="<?php echo $base_url ?>admin/resid.php" method="post">
2
<input name="image" type="file" accept="image/*" id="imguploadresid" />
3
</form>
4