Monday, June 02, 2014

Using FormData correctly

Using FormData to upload images via Ajax is easier than most examples you find on the Internet make it.  Just define your form in HTML, include as many files as you want, then pass the document element of the Form to the constructor of the FormData class.

Most examples in the wild suggest something like this:

var data = new FormData();
jQuery.each($('#file')[0].files, function(i, file) {
    data.append('file-'+i, file);
});

If your form is defined in your HTML, it is easier to pass the form into the constructor than it is to iterate and add images.
$('#my-form').submit( function(e) {
    e.preventDefault();

    var data = new FormData(this); // this is the form element

    $.ajax({
            url: '/my_URL/',
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',     
            success: function(data){
            ...

No comments: