1

These two codes (1)(2) seems to work in the same manner to me.

My questions are:
1) Are these two codes equivalent?
2) If yes why? If not what should I prefer and why?


(1)

$.ajax({
    url: backendRouter.generate('feedback_send'),
    type: 'POST',
    dataType: 'json',
    data: data
    success: callback,
    done: function () {
        // some code
    }
});

(2)

$.ajax({
    url: backendRouter.generate('feedback_send'),
    type: 'POST',
    dataType: 'json',
    data: data
    success: callback
}).done(function () {
    // some code
});
Lorraine Bernard
  • 13,000
  • 23
  • 82
  • 134
  • This post might serve you with some good info: http://stackoverflow.com/questions/8847829/what-is-diffrence-between-success-and-done-method-of-ajax – Jonas Geiregat Aug 23 '12 at 08:36

1 Answers1

3

Yes, the two codes are equivalent, except that (by mistake?) you've left success: callback in the latter.

However IMHO the latter is preferred as deferred objects are far more flexible than supplying a callback directly to $.ajax.

In particular, using deferred objects allows for much better separation of logic and responsibility between initiating the AJAX call and the processing of the results of that call. Also, some of the AJAX helper functions don't support an error callback. If I write:

function doAjax() {
    return $.get(...);
}

I can then attach arbitrary numbers of done and fail handlers to the result of that function call, without ever having to pass those handlers into the doAjax function.

I can also combine the returned promise() object with other promises using $.when(), $.pipe(), etc, for very powerful synchronisation between multiple asynchronous events (including other AJAX calls, timers, animations, etc). I can't do that using success:

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • +1 thanks for your answer. Actually related to your reply I opened another question [How to spy jQuery AJAX request with Jasmine?](http://stackoverflow.com/questions/12088029/how-to-spy-jquery-ajax-request-with-jasmine). Could you give a look, thanks. – Lorraine Bernard Aug 23 '12 at 08:52