1

I am trying to submit form data with jQuery but it is showing some strange behavior. Let me explain what is mean by "strange". If I use the HTML code below:

<form id="upload" enctype="multipart/form-data">
    <input type="text" name="myfile" id="myfile" />
</form>

and this jQuery code:

$("#myfile").bind("change",function() {
    var data = $('form#upload').serialize();
        alert(data);
});

It shows the expected result but if I change the HTML code to:

<form id="upload" enctype="multipart/form-data">
    <input type="file" name="myfile" id="myfile" />
</form>

It simply does not show anything. I've also tried FormData() instead of serialize() but same result. I've also tried reading data on server-side but it also shows the same. I'm Using PHP as server-side language.

Moin
  • 1,087
  • 1
  • 9
  • 19

1 Answers1

1

The file element is a bit different from others. To submit file in js, you have to use different way. You can use plugin like : jQuery File Upload

JoDev
  • 6,633
  • 1
  • 22
  • 37
  • http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously-with-jquery – JoDev Mar 07 '13 at 13:42
  • But we can use `FormData()` to handle files too see [another question](http://stackoverflow.com/questions/5392344/sending-multipart-formdata-with-jquery-ajax) about it which clearly shows it. And so does [Mozilla](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/FormData) – Moin Mar 07 '13 at 13:45
  • Yes, but you aren't cross browsers. Can you post your FormData code? To use FormData, you don't have to just replace serialize by formData, you have to implement a new FormData... like showed in the link you post – JoDev Mar 07 '13 at 13:51
  • I'm using the latest Google Chrome version and this is what happening in it. – Moin Mar 07 '13 at 13:52
  • `var formData = new FormData($('form#upload')[0]); alert(formData); $.ajax({ url: '../uploader.php', type: 'POST', xhr: function() { myXhr = $.ajaxSettings.xhr(); if(myXhr.upload){ myXhr.upload.addEventListener('progress',progress, false); } return myXhr; }, beforeSend: beFore, success: Okay, error: err, data: formData, cache: false, contentType: false, processData: false });` – Moin Mar 07 '13 at 14:06