Loading PHP AJAX Image Using FormData

I am relatively new to jQuery and Ajax functions, but have been working with Ajax forms in the last few days. When I tried to download images, I had a problem downloading files. Although I was looking for resources, I could not find anything useful, because they seem overly complex with meaningless additions or have no explanation, which does not help me learn further.

I wrote this code to handle image loading in Ajax:

$(function() { $('.input_photo').on("change",function() { var formData = new FormData($('form.upload-form')); $.ajax({ url: "upload.php", type: "POST", data: formData, success: function (msg) { alert(msg) } }); }); }); 

This sends the request to the upload.php file, however the data is not sent, basically my form is literally like this:

 <form class="upload-form"> <input type="file" name="input_photo" class="input_photo" /> </form> 

No data is passed in the headers at all, and I assume that I am accessing it through PHP with an array of $_POST['data'] or $_FILES ? Someone with better knowledge, please help explain this, it would be great to understand this further. Thanks.

+5
source share
3 answers

This will work for one or more files.

 $('input:file').on('change', function () { var data = new FormData(); //Append files infos jQuery.each($(this)[0].files, function(i, file) { data.append('file-'+i, file); }); $.ajax({ url: "my_path", type: "POST", data: data, cache: false, processData: false, contentType: false, context: this, success: function (msg) { alert(msg); } }); }); 

Then

 $_FILES['file-0'] $_FILES['file-1'] [...] 

But be careful if using FormData does not work in IE before IE10

+9
source

You need to set processData and contentType in your ajax call (also the added identifier to the input element to extract the contents of the file).

HTML

  <form class="upload-form"> <input type="file" id="photo" name="input_photo" class="input_photo" /> </form> 

Js

  $(function() { $('.input_photo').on("change",function() { var file = document.getElementById("photo").files[0]; //fetch file var formData = new FormData(); formData.append('file', file); //append file to formData object $.ajax({ url: "upload.php", type: "POST", data: formData, processData: false, //prevent jQuery from converting your FormData into a string contentType: false, //jQuery does not add a Content-Type header for you success: function (msg) { alert(msg) } }); }); }); 
+1
source

Try the following:

 var formData = $('form.upload-form').serialize(); 
-1
source

All Articles