5

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?

Zach Lysobey
  • 14,959
  • 20
  • 95
  • 149

2 Answers2

1

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
});
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

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:

  1. abstract away data fetching from data processing
  2. add multiple handlers, even after the AJAX call completed
  3. use .fail handlers on AJAX helpers that don't have error: parameters
  4. use .pipe to post-process the data before passing it on to other handlers
  5. synchronise with other asynchronous events

and 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.

Community
  • 1
  • 1
Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • was just gonna comment and ask @Guffa if he agreed with this convention. Its much easier for me to memorize one usage than both. Can you think of any situation where there would be an appreciable benefit to other approach? If not, I'm getting in the boat with you. – Zach Lysobey Feb 18 '13 at 22:52
  • There are numerous benefits of the deferred approach over the old style and it lets you do things that you just can't easily do with the old `success:` style handlers. – Alnitak Feb 18 '13 at 22:54
  • Great, just read [your other answer](http://stackoverflow.com/a/14754681/6782) too (+1), great stuff. TIL – Zach Lysobey Feb 18 '13 at 22:55