10

I need to upload a photo on a server using ajax. I have set up the form the javascript as well, but the FormData object is always empty! I have tried various ways to reference the actual form, but still not working.

fiddle example: https://jsfiddle.net/cjngvg8a/

Thanks!

html:

<form id="profileImageForm" action="update.php" method="post" enctype="multipart/form-data">
<input type="text" value="hello" name="test" />
<input type="file" name="profile_pic" id="image_upload"/>
<input type="submit" value="Save"/>
</form>

js:

$('#profileImageForm').on('submit',(function(e) {
    e.preventDefault();     
    var formData = new FormData(this);

    console.log(formData);

    $.ajax({
        type:'POST',
        url: $(this).attr('action'),
        data:formData,
        cache:false,
        contentType: false,
        processData: false,
        success:function(data){
            console.log("success");
            console.log(data);
        }
    });
}));
Edmond Tamas
  • 3,148
  • 9
  • 44
  • 89

1 Answers1

29

The data in a FormData object is not revealed by inspecting it with console.log(). It is there, you just can't see it.

If you examine the Net tab of your developer tools, you can see the form content is being uploaded.

Screenshot

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335