Easy-does-it Ajax file uploads

E

Remember the days where we had to pull out all the stops when trying to make Ajax file uploads work? Nasty iFrame implementation and all? Well, no more!

We’re finally reaching a point where it’s becoming safe to use a new HTML5 feature called “the formdata object”. What this comes down to is basically a better version of the old XHR object used to make asynchronous requests to the browser. And guess what? Indeed! It supports file uploads as well! Oh joy!

Although the formdata api has been in development for several years, it’s only recently become supported across popular browser (three guesses who was lagging behind…). As of now, it’s support is pretty broad and I for one feel safe applying it to production sites (IE is supporting it from version 10 onwards,  for more details on browser support have a look here).

Please see below some sample code I used in a recent update to our Databased software. We’re implementing CSV uploads and since the process starts from within a Bootstrap modal, I figured it would be nicer to use an Ajax implementation rather then sending the user to a different page to complete the process. Works like a charm!

$('#newTableModal').on("submit", "form#uploadForm", function(){

    var form = $(this);
    var formdata = false;

    if (window.FormData){
        formdata = new FormData(form[0]);
    }

    var formAction = form.attr('action');

    $.ajax({
        url : formAction+"/"+_theDB,
        data : formdata ? formdata : form.serialize(),
        cache : false,
        contentType : false,
        processData : false,
        dataType: "json",
        type : 'POST'

    }).done(function(response){

        //your response hanndling

    })

    return false;

})

About the author

Matt Naus

I have been building web applications and other digital products for more then a decade. Currently on an exciting journey discovering the ins and outs of content marketing while growing my newest business. Dedicated to helping digital agencies and entrepreneurs around the world succeed!

By Matt Naus

Recent Posts

Recent Comments

Archives

Categories

Meta