Submit file input via AJAX with jQuery the easy way

Learn how to submit File input through an AJAX webform the easy way.

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
    } );
  } );