Sending files over Ajax requests with jQuery

Published

Estimated Reading Time: 1 minute

If you’ve been writing jQuery, you’re probably fond of writing your code this way when submitting forms with ajax

$('form').on('submit',function(e){
  e.preventDefault();
  var data = $(this).serialize();
  $.ajax({
    type:"POST",
    data:data,
    url: yourUrl
  }).done(function(response){
    console.log(response);
  }).fail(function(){
    console.log("It failed");
    });

});

and for those using older versions of jQuery or haven’t realized the essence of promises, it should be something like this you have:

$('form').on('submit',function(e){
  e.preventDefault();
  var data = $(this).serialize();
  $.ajax({
    type:"POST",
    data:data,
    url: yourUrl
    success:function(response){
     console.log(response);
    },
   error:function(){
     console.log("It failed");
  });

});

Either way you have it, a problem you will encounter when working with file inputs will be that your files do not get uploaded. This is because XMLHttpRequests (XHR)  was not supporting Form Data Objects with file inputs.

According to the standards by mozilla support has been added for XHR Level 2. This makes it easy to transfer files with Ajax requests. All you need is a little tweak in your code.

If you have the following HTML

<form action="" id="compform">
<input type="text" name="title">
<input type="file" name="file">
</form>

You can handle the file upload in ajax as shown here:

$('form').on('submit',function(e){
    e.preventDefault();
    var data = new FormData($('#compform')[0]);
    $.ajax({
      type:"POST",
      data:data,
      url: yourURL,
      processData: false,
      contentType: false
    }).done(function(response){
      console.log(response.id);
    }).fail(function(){
      console.log("It failed");
      });

  });

This was stated by the Mozilla Developer Network here

show comments