What to use in Ajax, Success or done?

Asked

Viewed 17,718 times

21

Sometimes I see them using success, sometimes I see .done, to process the response obtained in the request.

  • Which one should I use?
  • Is there any difference between the two? Which?

The same thing for .error and .fail.

I use jQuery 3.2.1.

  • The .done is always executed, while .success is only called if success occurs. I do not know the distinction between .fail and .error

  • It must be the same

  • 2

    They are not. The methods done and fail are related to function return $.ajax, that is a Promise. Methods success and error sane callbacks executed within the function itself.

2 answers

28

Conceptually they are not the same thing, but the result produced is exactly the same. The functions success and error are called callbacks. In turn, the functions done and fail are methods of a Promise.

Difference between Promise and callback

The result is exactly the same because jQuery uses its own methods done and fail to perform the functions success and error. See the code snippet taken from official repository (line 662):

// Install callbacks on deferreds
completeDeferred.add( s.complete );
jqXHR.done( s.success );
jqXHR.fail( s.error );

In this case, s.success refers to the success past in options, as well as s.error refers to error.

Which one to use?

If you have only one function success and error, makes no difference. Use which one you prefer. Use done and fail are useful when you need to perform multiple functions in each event:

$.ajax("dominio.com")
    .done(fazAlgo1)
    .done(fazAlgo2)
    .fail(deuErrado1)
    .fail(deuErrado2);

Using success and error you cannot assign multiple callbacks. There is still the callback complete which is executed at all times, after the execution of success or error. In this case, the similar method in Promise would be the always.

For more information, please read the official documentation cited in another answer

Note: it is important to stress that the methods .success and .error which the documentation cites as obsolete are not callbacks success and error. They are, in fact, methods present in the Promise in older versions of jQuery. The functions callbacks can still be used.

Example using callbacks:

Using the function callback success.

$(() => {

  $.ajax({
    url: "https://jsonplaceholder.typicode.com/users",
    method: "get",
    dataType: "json",
    success: users => {
      $(users).each(i => {
        console.log(users[i].name);
      });
    },
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Example using Promise

Using the method done of the object Promise returned by $.ajax.

$(() => {

  const request = $.ajax({
    url: "https://jsonplaceholder.typicode.com/users",
    method: "get",
    dataType: "json"
  });
  
  request.done(users => {
    $(users).each(i => {
      console.log(users[i].name);
    });
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Example using obsolete methods of Promise (OBSOLETE)

Using the method success of the object Promise returned by $.ajax.

This method is only present for reference, but it is obsolete since version 1.8 of jQuery and has been removed completely in jQuery 3. Do not use it.

$(() => {

  const request = $.ajax({
    url: "https://jsonplaceholder.typicode.com/users",
    method: "get",
    dataType: "json"
  });
  
  request.success(users => {
    $(users).each(i => {
      console.log(users[i].name);
    });
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Example using fetch

An alternative is in tests at the time called fetch. The function is basically what $.ajax does, I believe, but will be native to the browser, not needing to import a third-party library. A GET request, for example, could be made like this:

const request = new Request("https://jsonplaceholder.typicode.com/users", {"method": "GET"});

fetch(request).then(response => {
  if (response.ok) {
    return response.json().then(data => {
      data.forEach(user => {
        console.log(user.name);
      });
    });
  }
});

In my view it will be much better to use, not only because it is native, but because it is semantic, working with objects of the type Request, Response, Headers, etc. But remember, it is still in the testing phase.


Other readings

What are javascript (promises)?

How to really learn how to use javascript promises?

What is a callback?

What is the difference between Function() {} and () => {}? Why doesn’t $http.get work?

  • UHMMM now I understand the difference pretty cool

1

According to the documentation of jQuery, follows below the status

jqXHR.done(Function( data, textStatus, jqXHR ){});
An alternative to the return option of Success.


jqXHR.fail(Function( jqXHR, textStatus, errorThrown ){});
An alternative to error return, the . fail() method has replaced the . error() method that is now obsolete.
jqXHR.Always(Function( data|jqXHR, textStatus, jqXHR|errorThrown){}); (added in jQuery 1.6)
An alternative to the call option when the request is complete. The . Always() method has replaced the . complete() method that is now obsolete.

If it is a successful request, the arguments of the function are the same as . done(). For requests that errors have occurred, the arguments are equal to . fail().


jqXHR.then(Function( data, textStatus, jqXHR ) {}, Function( jqXHR, textStatus, errorThrown ){});
Incorporates method functionality . done() and . fail(), allowing (from jQuery 1.8) working with Promise.
Important: jqXHR.Success(), jqXHR.error() and jqXHR.complete() returns have been removed since jQuery version 3.0. You can use jqXHR.done(), jqXHR.fail() and jqXHR.Always() as an alternative.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.