As far as I can tell from the documentation, there are two distinct ways of handling the response from a $.ajax()
call.
1) With functions passed into $.ajax()
's settings object:
$.ajax({
success: function(){ ... },
error: function(){ ... }
});
2) As chainable "callback hooks"
$.ajax({...})
.done(function(){ ... })
.fail(function(){ ... })
What are the important distinctions between these two approaches, and when should I choose one over the other?
If you are attaching the function directly in the call, there isn't much difference in the usage. The difference comes when you want to have the callback function somewhere else.
Sending the callback function into a method:
function callForMe(callback) {
$.ajax({
url: '...',
success: callback
});
}
callForMe(function(data){
// handle the response
});
Return the promise from a method, waiting for the response later:
function callFormMe() {
return $.ajax({
url: '...'
});
}
var promise = callForMe();
// later on:
promise.done(function(data){
// handle the response
});
I always use the new deferred object (i.e. chainable .done
, .fail
etc) version, even though in many cases there's no saving in code length.
The reason is that it allows me to decouple the details of making the AJAX call from the subsequent handling of the response.
The decoupling allows me to:
.fail
handlers on AJAX helpers that don't have error:
parameters.pipe
to post-process the data before passing it on to other handlersand all without ever having to pass a callback directly to the AJAX call.
See this answer where I gave more concrete examples of the benefits.
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