Search code examples
jqueryjquery-file-upload

jquery file upload not working with jquery 3.x


My script works fine with jQuery 1.x and 2.x, but it doesn't work with jQuery 3.x

imageInput.fileupload();
var jqXHR = imageInput.fileupload('send', {
    files: files,
    formData: $.extend({csrfmiddlewaretoken: csrftoken}, attachmentData),
    url: {{ id }}_settings.url.upload_attachment,
})
.success(function (result, textStatus, jqXHR) {
    $.each(result.files, function (index, file) {
        console.log('success');
    });
})
.error(function (jqXHR, textStatus, errorThrown) {
    console.log('error occurred.');
});

The FF browser complains that success and error function is NOT found.

jQuery.Deferred exception: imageInput.fileupload(...).success is not a function 
....
undefined

This is the error message. Thank you for your help.


Solution

  • jQuerys success and error were initially part of $.ajax, as in

    $.ajax({
        success : function() {},
        error   : function() {}
    })
    

    But as $.ajax starter returning Deferreds, it changed to done and fail

    $.ajax({}).done().fail()
    

    This caused some confusion, so identical methods called success and error was added as well, so one could do

    $.ajax({}).success().error()
    

    The decision to remove success and error was made in the release of jQuery 3.x

    https://jquery.com/upgrade-guide/3.0/#breaking-change-special-case-deferred-methods-removed-from-jquery-ajax

    You can just swap in done and fail as direct replacements in your code for success and error as the Fileupload plugin uses jQuery's $.ajax under the hood.
    jQuery's Deferreds are now Promise A+ compliant, so one could use then and catch as well