file upload ajax call


How to:good reference:

You make a webform that you’d like to be hipster about and submit by AJAX. jQuery makes this a breeze so there’s no problem. You probably use serialize() to encode the form data, and all is well.

But then you want to include a file input field with the form submission and your remote AJAX handler doesn’t receive it at all. Well, serialize() says that it doesn’t serialize form data so now what? The answer is the FormData object. The FormData object lets you compile a set of key/value pairs (including File input) to send using XMLHttpRequest (an AJAX call) and the transmitted data is in the same format that the form’s submit method would use to send the data if the form’s encoding type were set to multipart/form-data.

And now to tie things together, an example of submitting an AJAX webform with jQuery. Note how the FormData object is used to “serialize” the form and how jQuery is set to not process the data nor set the content type.

$( '#my-form' )

  .submit( function( e ) {

    $.ajax( {

      url: '',

      type: 'POST',

      data: new FormData( this ),

      processData: false,

      contentType: false

    } );


  } );

2015-03-31 12:11:54gstlouis

had to add form element to capture file with “new FormData” as I was not getting the form element my listener was on $(':file').change so I had to go get the form element raw index.

  • new FormData needs the raw element index ex. var formData = new FormData($(this).closest('form')[0]);
2015-03-31 12:13:13