Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery ajax: when to use callback hooks vs settings functions?

Tags:

jquery

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?

like image 320
Zach Lysobey Avatar asked Nov 04 '22 04:11

Zach Lysobey


2 Answers

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
});
like image 82
Guffa Avatar answered Nov 12 '22 15:11

Guffa


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.

like image 22
Alnitak Avatar answered Nov 12 '22 16:11

Alnitak