I use:
var jqXHR = $.ajax(settings);
jqXHR.success(function(result){});
jqXHR.error(function(result){});
jqXHR.complete(function(result){});
But version 1.5 has added the deferred object.
Q: In general, when do you use success, error and complete methods vs. the new hotness of deferred then, done and fail?
Deferred() method in JQuery is a function which returns the utility object with methods which can register multiple callbacks to queues. It calls the callback queues, and relay the success or failure state of any synchronous or asynchronous function.
The jqXHR (jQuery XMLHttpRequest) replaces the browser native XMLHttpRequest object. jQuery wraps the browser native XMLHttpRequest object with a superset API. The jQuery XMLHttpRequest (jqXHR) object is returned by the $. ajax() function. The jqXHR object simulates native XHR functionality where possible.
You can use jQuery to support both synchronous and asynchronous code, with the `$. when` function, and your code doesn't have to care whether or not it's async.
Definition and UsageIf the defer attribute is set, it specifies that the script is downloaded in parallel to parsing the page, and executed after the page has finished parsing. Note: The defer attribute is only for external scripts (should only be used if the src attribute is present).
For $.ajax()
and family .success
is merely a synonym for Deferred's .done
, and likewise .error
is a synonym for .fail
.
So in fact the examples you show are already deferred methods, but with different names.
.complete
is mostly a synonym for the new jQuery 1.6 .always
, and you can get the same effect using $.then(cb, cb)
, which will cause cb
to be invoked whether the AJAX call succeeds or not. I believe there are minor differences in which parameters are passed to the "fail" callbacks between the .complete
, .always
and $.then
variants.
I personally prefer to use the Deferred version of those named functions, because then you don't need to worry about whether your deferred objects are jqXHRs or not. Only jqXHRs
have .success
, .error
, and .complete
, but every Deferred (including jqXHRs) has .done
, .fail
and .always
.
EDIT it seems the jQuery devs agree with me - they've announced that .success
, .error
and .complete
will be deprecated in jQuery 1.8
Deferred is meant to replace jqXHR and abstracts the idea of success and error beyond ajax.
A quick look at the source code: jQuery 1.6.1
// completeDeferred is resolved in only one place.
completeDeferred.resolveWith( callbackContext, [ jqXHR, statusText ] );
deferred.promise( jqXHR ); // this attaches the promise methods to jqXHR
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
jqXHR.complete = completeDeferred.done;
I made a cheese slide show for work about how deferred is useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With