Call to jquery ajax - .fail vs. :error

JqueryAjaxCallback

Jquery Problem Overview


Which one should I use?

Is there any reason to use one rather than the other?

Is one better for error handling?

$.ajax({
    url: url,
    data: { start: start, end: end }
}).done(function(data, textStatus, jqXHR) {
    $('#myElement').append(data);
}).fail(function() {
    // report error    
});

OR

$.ajax({
    url: url,
    data: { start: start, end: end },
    success: function(data, textStatus, jqXHR) {
        $('#myElement').append(data);
    },
    error: function(jqXHR, textStatus, errorThrown) {
        // report error
    }
});

Jquery Solutions


Solution 1 - Jquery

The two options are equivalent.

However, the promise-style interface (.fail() and .done()) allow you to separate the code creating the request from the code handling the response.

You can write a function that sends an AJAX request and returns the jqXHR object, and then call that function elsewhere and add a handler.

When combined with the .pipe() function, the promise-style interface can also help reduce nesting when making multiple AJAX calls:

$.ajax(...)
    .pipe(function() { 
        return $.ajax(...);
    })
    .pipe(function() { 
        return $.ajax(...);
    })
    .pipe(function() { 
        return $.ajax(...);
    });

Solution 2 - Jquery

Just to freshen this up...

The success and error approach have been deprecated as of jQuery 1.8.

jQuery Ajax >Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

Solution 3 - Jquery

Using the chainable deferred object promise style allows for a cleaner structure and the use of always.

let data = {"key":"value"}

$.ajax({
    type: 'PUT',
    url: 'http://example.com/api',
    contentType: 'application/json',
    data: JSON.stringify(data), 
}).done(function () {
    console.log('SUCCESS');
}).fail(function (msg) {
    console.log('FAIL');
}).always(function (msg) {
    console.log('ALWAYS');
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPeteGOView Question on Stackoverflow
Solution 1 - JquerySLaksView Answer on Stackoverflow
Solution 2 - JqueryslohrView Answer on Stackoverflow
Solution 3 - Jqueryow3nView Answer on Stackoverflow