Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery $.post deferred

Tags:

jquery

How do I use a deferred with jQuery's $.post? I tried:

var myFunc = function(data, textStatus, jqXHR) {
    console.log(data);
};
var post = $.post("/url/", someData);
$.when(post).done(myFunc);

The usual

$.post("/url/", someData, function(data) { myFunc(data) });

works fine (after changing the myFunc signature).

$.when... doesn't work, and no errors show me failures. What exactly is the .done() function passing into myFunc?

like image 685
atp Avatar asked Sep 12 '26 11:09

atp


1 Answers

The jQuery ajax functions return a jqXHR which is itself a deferred object (it implements the Promise interface). So no need for $.when().

There is also no need to use a named function expression for myFunc, a normal function declaration is fine.

function func1(data, textStatus, jqXHR) {
    console.log('success', data);
}

function func2(jqXHR, textStatus) {
    console.log('done', textStatus);
}

$.post('/url/', someData).success(func1).done(func2);

Demo: http://jsfiddle.net/mattball/ng7zT/


What exactly is the .done() function passing into myFunc?

This is documented at the jqXHR link above, and also at $.post.

The success callback function is passed the returned data, which will be an XML root element or a text string depending on the MIME type of the response. It is also passed the text status of the response.

As of jQuery 1.5, the success callback function is also passed a "jqXHR" object (in jQuery 1.4, it was passed the XMLHttpRequest object).

like image 111
Matt Ball Avatar answered Sep 14 '26 07:09

Matt Ball