Search This Blog

Wednesday, September 20, 2017

AJAX File Uploads

Introduction

Ajax files uploads used to be complex and mostly done with Flash which was uneasy and had a lot of problems.

Implementation


Today, we will show to do an AJAX Files uploads with only JQuery


var myfile= document.getElementById("UploadBatchFile").files; 
var data = new FormData();
data.append('file', myfile[0]);
data.append('id',$("#UploadBatchID").val());

$.ajax({"url":"load.php", 
         data:data,
         type:"POST",dataType:"JSON",
         contentType: false,
         processData: false,
         cache: false,
         success:function(data) {
          //Write your success code
         }
  }); 


Things to note:


  1. Getting the file input by $("#...") won't work and you have to use
    document.getElementByID 
  2. files is an array so it can work with multiple files as well.
  3.          contentType: false,
             processData: false,
             cache: false
    Must be added for it to work with $.ajax.