0
votes

According to the official JQuery documentation:

jqXHR.always(function(data|jqXHR, textStatus, jqXHR|errorThrown) { });

An alternative construct to the complete callback option, the .always() method replaces the deprecated .complete()method.

In response to a successful request, the function's arguments are the same as those of .done(): data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail(): the jqXHR object, textStatus, and errorThrown. Refer to deferred.always() for implementation details.

And let's say that I have the following ajax script :

$.ajax({

    url: 'myPHPScript.php',
    type: 'POST',
    data: {
        param_1: 'value_1',
        param_n: 'value_n'…
    },
    username: 'myLogin',
    password: 'myPassword',
    beforeSend: function() {
        alert('The object was created but not yet initilized');
    }
}).done(function(data, textStatus, jqXHR) {
    alert('All the request was sent and we received data');
}).fail(function(jqXHR, textStatus, errorThrown) {
    alert('Error: the following error was occurred: ' + textStatus + ' Status : ' + jqXHR.Status);
}).always(function() {
    // Here is my problem
});

In the .always() function, how can I specify a different function for each statement, I mean when the Deferred is resolved, the always() function gets passed the following params (data, textStatus, jqXHR) however if the deferred is rejected it gets passed (jqXHR, textStatus, errorThrown).

Thanks

1
Surely that's what .done() and .fail() are for, you can have multiple such callbacks. - Orbling
@Orbling, thanks for your replay, I know that each one off .done() and .fail() does a portion of what I am looking for, but as you may know .fail() is executed only and only if the other didn't success, in other means they are not executed together each time, however, .always() is all the time called, that's why it is important, but my problem as I said is to make a separate portion of code to be executed per differed status. - ghaliloo
Could you not just check the first argument to see if it was a jqXHR then? - Orbling

1 Answers

3
votes

The only good solution is not using the arguments in always - if you need code specific to the success/failure of the AJAX call out them in done or fail callbacks. Usually the always callback is a place where you do things such as re-enabling a button, hiding a throbber, etc. All those are things where you do not care about the result of the request.

Besides that, you could check arguments.length for the number of arguments and then access the arguments via arguments[0] etc. But relying on the argument count is a bad idea since it might not be future-proof.