Search code examples
jqueryajaxjquery-deferredabort

jQuery ajax requests as Deferred - wrap fail callbacks


My web-app has all its ajax calls in the form

$.post(url, data, successCallback).fail(failCallback)

My need is to introduce a mechanism of abort if some circumstances occur.

Since calling .abort() also triggers the failCallback, I'm trying to figure out a way (if any), to intercept the abort failure and do not trigger the callback.


Solution

  • I don't thing you really can do that, when the abort is called, the ajax request fails, and the fail method is called.

    The closest I think you'll get is checking the error and calling the function conditionally, as aborting will throw abort as the error (and as status)

    $.post(url, data, successCallback).fail(function(xhr, status ,err) {
       if (err !== 'abort')
           failCallback();
    });
    

    FIDDLE