Jquery ajax: when to use callbacks versus settings?

As far as I can tell from the documentation , there are two different ways to handle a response from a call $.ajax().

1) With functions passed to the $.ajax()settings object :

$.ajax({
    success: function(){ ... },
    error: function(){ ... }
});

2) Like chain “back hooks”

$.ajax({...})
    .done(function(){ ... })
    .fail(function(){ ... })

What are the important differences between the two approaches, and when should I choose one after the other?

+5
source share
2 answers

If you connect the function directly to the call, the difference in use is small. The difference arises when you want to have a callback function somewhere else.

Sending a callback function to a method:

function callForMe(callback) {
  $.ajax({
    url: '...',
    success: callback
  });
}

callForMe(function(data){
  // handle the response
});

Return the promise of the method, waiting for a response later:

function callFormMe() {
  return $.ajax({
    url: '...'
  });
}

var promise = callForMe();
// later on:
promise.done(function(data){
  // handle the response
});
+1
source

(.. .done, .fail ..), .

, AJAX .

:

  • , AJAX-
  • .fail AJAX, error:
  • .pipe , .

AJAX.

. , .

+1
source

All Articles