Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does JQuery.getJSON() have a success and a done function?

Tags:

jquery

getjson

The JQuery documentation for getJSON shows an example of:

var jqxhr = $.getJSON( "example.json", function() {
  console.log( "success" );
})
  .done(function() {
    console.log( "second success" );
  })
  .fail(function() {
    console.log( "error" );
  })
  .always(function() {
    console.log( "complete" );
  });

What's the difference between the success function (passed as the 2nd parameter) the the done() function? They seem to be the same thing.

like image 704
David Thielen Avatar asked Apr 14 '14 16:04

David Thielen


People also ask

What is jQuery getJSON?

jQuery getJSON() Method The getJSON() method is used to get JSON data using an AJAX HTTP GET request.

What is the difference between getJSON and Ajax in jQuery?

getJSON() is equal to $. ajax() with dataType set to "json", which means that if something different than JSON is returned, you end up with a parse error. So you were mostly right about the two being pretty much the same :).

How does Ajax success work?

AJAX success is a global event. Global events are triggered on the document to call any handlers who may be listening. The ajaxSuccess event is only called if the request is successful. It is essentially a type function that's called when a request proceeds.


2 Answers

Initially, jQuery asynchronous functions weren't returning promises, you had to use the callback.

Then they added the deferred (promise) system but kept the callbacks for compatibility (and because not everybody like deferred).

From the Deferred object documentation :

In JavaScript it is common to invoke functions that optionally accept callbacks that are called within that function. For example, in versions prior to jQuery 1.5, asynchronous processes such as jQuery.ajax() accept callbacks to be invoked some time in the near-future upon success, error, and completion of the ajax request.

jQuery.Deferred() introduces several enhancements to the way callbacks are managed and invoked. In particular, jQuery.Deferred() provides flexible ways to provide multiple callbacks, and these callbacks can be invoked regardless of whether the original callback dispatch has already occurred. jQuery Deferred is based on the CommonJS Promises/A design.

like image 171
Denys Séguret Avatar answered Oct 12 '22 10:10

Denys Séguret


They are the same thing. The done function is meant to work like Promise That way you can install handlers from the result of the ajax call. It even works if you call done after the asynchronous call finished (by storing the return value)

like image 36
Juan Mendes Avatar answered Oct 12 '22 12:10

Juan Mendes