Phillip Senn
Phillip Senn

Reputation: 47635

An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method

I'm confused by the wording in the jQuery documentation:

jqXHR.done(function( data, textStatus, jqXHR ) {});

An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details.

I'm not confused about jqXHR.success - that apparently is deprecated. But because jqXHR.done() is "an alternative construct", is the author saying to use .done or "the success callback option"?

Edit:

Maybe the author is saying that the .done method is an alternative because it gives you more features than the success callback.

Upvotes: 0

Views: 599

Answers (1)

Kevin B
Kevin B

Reputation: 95066

jqXHR.done is an alternative to the success callback option, for example,

$.ajax("foo.php",{
    success: successHandler
})

$.ajax(...).success() is of course deprecated.

It isn't saying you should use .done over the success callback option, it's just pointing out that it is a valid alternative. Use whatever makes sense in your code. You can use both if needed, the success callback option will be bound first, therefore it will get triggered first.

The main difference between using .done and success: is that .done() can be applied to a jqXHR after the request has been sent/received. For example,

var request = $.ajax(...);

request.done(function(){
    console.log("It's done!");
});

function doSomething () {
    request.done(function(result){
        console.log(result);
    })
}

$("#someel").click(doSomething);

Now, every time you click #someel, it will console.log the result of the ajax request without having to worry with whether or not it is done yet.

Or, maybe you want to get some content, but instead of going to the server on every click, just use the existing data.

$("#someel").click(function(e){
    e.preventDefault();
    var $this = $(this);
    if (!$this.data("request")) {
        $this.data("request",$.ajax(...));
    }
    $this.data("request").done(function(result){
        console.log(result);
    });
});

now it will only go to the server on the first click, after that it will using the existing data.

Upvotes: 2

Related Questions