5

I am relatively new to jQuery and Ajax functions, but have been working with Ajax forms over the past few days. I have come to a problem with file uploads however when trying to upload images. Whilst looking for resources, I couldn't find anything useful because they seem to be over-complicated with pointless extras or have no explanation whatsoever, which doesn't help me to learn any further.

I have wrote this code to handle the image upload 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 a request to the upload.php file, however no data is sent, basically my form is literally this:

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

No data seems to be passed in the headers whatsoever and I assume I would access it through PHP with $_POST['data'] array or $_FILES? Someone with better knowledge please help to explain this, it'd be great to understand this further. Thanks.

0

3 Answers 3

9

This will work for one or multiple 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 that using FormData doesn't work on IE before IE10

Sign up to request clarification or add additional context in comments.

1 Comment

Worked perfectly first time, although I changed it to .on('change') since live is deprecated. Thank you very much.
2

You need to set processData and contentType in your ajax call ( also added id to your input element in order to fetch the file contents).

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 Comment

Just tried pretty much this exact code from another question and it just passes an empty $_FILES array for some reason.
-2

Try with this:

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

1 Comment

That only posts form data, not file data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.