0

Both examples bellow return the same result:

Using success - error

$.ajax({
  url: 'https://jsonplaceholder.typicode.com/users',
  type: 'GET',
  success: function(response) {
    response.map(item => $('#data-list').append(`<li>${item.name}</li>`));
  },

  error: function(xhr) {
    console.log(xhr.status);
    console.log('There was an error');
  }
});

Using done - fail

$.ajax({
  url: 'https://jsonplaceholder.typicode.com/users',
  type: 'GET'
})
  .done(function(response) {
    response.map(item => $('#data-list').append(`<li>${item.name}</li>`));
  })
  .fail(function(jqXHR, textStatus) {
    console.log('Request failed: ' + textStatus);
  });

What exactly is the difference? Does it have something to do with callback and promises?

user1941537
  • 6,097
  • 14
  • 52
  • 99
  • 1
    **Deprecation Notice:** The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead. – Atanu Feb 04 '19 at 13:15
  • 1
    It's just different ways of doing the same thing. The `done`, `fail` handlers were added after `success`, `error` properties, simply to align jquery with [promise syntax.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). They both work. The later is more "modern". the later also allows you to return the result of your async function. – Liam Feb 04 '19 at 13:22
  • 2
    @Atanu that is the `$.ajax.sucess()` call backs, not `$.ajax({succes:...})`. These are not deprecated – Liam Feb 04 '19 at 13:23
  • 1
    Possible duplicate of [jQuery.ajax handling continue responses: "success:" vs ".done"?](https://stackoverflow.com/questions/8840257/jquery-ajax-handling-continue-responses-success-vs-done) – Liam Feb 04 '19 at 13:24
  • @Liam, would it be right to say that done and fail handle the response as a promise, where success and error are just properties of $.ajax? – user1941537 Feb 04 '19 at 13:29
  • 1
    Kinda. Problem is these predate the adoption of promises. So they're actually an implementation of [jquery.Deferred](https://api.jquery.com/category/deferred-object/), which is jquery's version of promises, but differ slightly. – Liam Feb 04 '19 at 14:04

0 Answers0