Which one to use in Ajax, success or done?

17

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

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

Same thing for .error and .fail .

I use jQuery 3.2.1.

    
asked by anonymous 04.07.2017 / 22:18

2 answers

21

Conceptually they are not the same thing, but the result produced is exactly the same. The success and error functions 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 the done and fail methods to execute the success and error functions. See the code snippet taken from the 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 success passed in options , as s.error refers to error .

Which one to use?

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

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

Using success and error you can not assign multiple callbacks . There is also the callback complete that is always executed, after running success or error . In this case, the similar method in Promise would be always .

For more information, please refer to the official documentation quoted in the other response

  

Note: It is important to note that the .success and .error methods that the documentation cites as obsolete are not the callbacks success and error . These are actually methods in Promise in older versions of jQuery. The callbacks functions can still be used .

Example using callbacks :

Using the callback function 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>

ExampleusingPromise

UsingthedonemethodofthePromiseobjectreturnedby$.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>

ExampleusingObsoletePromisemethods

UsingthesuccessmethodofthePromiseobjectreturnedby$.ajax.

  

Thismethodispresentforreferenceonly,butithasbeendeprecatedsincejQueryversion1.8andhasbeencompletelyremovedinjQuery3.Donotuseit.

$(() => {

  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>

Exampleusingfetch

Analternativeisintestsatthemomentcalled fetch . The function is basically what $.ajax does, I think, but it will be native in the browser, not needing to import a third-party library. A GET request, for example, could be done 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 opinion, it will be much better to use, not only because it is native, but because it is semantic, working with objects of type Request , Response , Headers . But remembering, it is still in the testing phase.

Further readings

What are promises in javascript?

How do I really learn to use promises in javascript?

What is callback?

What is the difference between function () {} and () = > {} Why does not http.get work?

    
04.07.2017 / 22:32
1

According to the documentation for jQuery , below the statuses

  

jqXHR.done (function (data, textStatus, jqXHR) {});
  An alternative to the success return option.   

jqXHR.fail (function (jqXHR, textStatus, errorThrown) {});
  An alternative to the error return, the .fail () method replaced the .error () method that is obsolete today.    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 replaced the .complete () method that is obsolete today.      

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

jqXHR.then (function (data, textStatus, jqXHR) {}, function (jqXHR, textStatus, errorThrown) {});
  It incorporates the functionality of the .done () and .fail () methods, allowing (from jQuery 1.8) to work with Promise.    Important : The returns from jqXHR.success (), jqXHR.error () and jqXHR.complete () were removed from jQuery version 3.0. You can use jqXHR.done (), jqXHR.fail () and jqXHR.always () instead.
    
04.07.2017 / 22:57