Skip to content

Submit file input via AJAX with jQuery the easy way

How to upload a file with form file input using FormData API and jQuery.

Let’s assume that you have a webform and you would like to submit it with AJAX. jQuery makes this easy so there’s no problem – you can use jQuery 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 a jQuery 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 and not set the content type.

$( '#my-form' )
  .submit( function( e ) {
    $.ajax( {
      url: 'http://example.com/action/',
      type: 'POST',
      data: new FormData( this ),
      processData: false,
      contentType: false
    } );
    e.preventDefault();
  } );

Also read Uploading large files with AJAX and jQuery using FileReader API, another practical example on Planetjon.