I know how to use jquery ajax like this. In other words, I understand that .fail gets called on failure etc.
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
I also understand that $.ajax("example.php") returns an object representing a part of the DOM and that there are anonymous functions passed as parameters to done/fail/always. So far so good. I also get method chaining (or "cascading"): how a function call on an object returns the object, so you can just call the object again with the next method in the chain.
However, I am trying to understand how jquery "knows" which of the methods to call from the chain above. It's not like done returns and then fail (the next method in the chain) is called. So what's going on with this syntax? How does it work under the hood?
Actually, $.ajax() doesn't return object representing a part of DOM, but a promise.
You can read more about promises here.
Quote from the https://api.jquery.com/jQuery.ajax/
The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the
Promise interface, giving them all the properties, methods, and
behavior of a Promise (see Deferred object for more information).
These methods take one or more function arguments that are called when
the $.ajax() request terminates. This allows you to assign multiple
callbacks on a single request, and even to assign callbacks after the
request may have completed. (If the request is already complete, the
callback is fired immediately.) Available Promise methods of the jqXHR
object include: ...
Read more at https://api.jquery.com/category/deferred-object/
Related
I have been working with jQuery and AJAX for a few weeks now and I saw two different ways to 'continue' the script once the call has been made: success: and .done.
From the synopsis from the jQuery documentation we get:
.done(): Description: Add handlers to be called when the Deferred object is resolved.
success: (.ajax() option): A function to be called if the request succeeds.
So, both do something after the AJAX call has been completed/resolved. Can I use one or the other randomly? What is the difference and when one is used instead of the other?
success has been the traditional name of the success callback in jQuery, defined as an option in the ajax call. However, since the implementation of $.Deferreds and more sophisticated callbacks, done is the preferred way to implement success callbacks, as it can be called on any deferred.
For example, success:
$.ajax({
url: '/',
success: function(data) {}
});
For example, done:
$.ajax({url: '/'}).done(function(data) {});
The nice thing about done is that the return value of $.ajax is now a deferred promise that can be bound to anywhere else in your application. So let's say you want to make this ajax call from a few different places. Rather than passing in your success function as an option to the function that makes this ajax call, you can just have the function return $.ajax itself and bind your callbacks with done, fail, then, or whatever. Note that always is a callback that will run whether the request succeeds or fails. done will only be triggered on success.
For example:
function xhr_get(url) {
return $.ajax({
url: url,
type: 'get',
dataType: 'json',
beforeSend: showLoadingImgFn
})
.always(function() {
// remove loading image maybe
})
.fail(function() {
// handle request failures
});
}
xhr_get('/index').done(function(data) {
// do stuff with index data
});
xhr_get('/id').done(function(data) {
// do stuff with id data
});
An important benefit of this in terms of maintainability is that you've wrapped your ajax mechanism in an application-specific function. If you decide you need your $.ajax call to operate differently in the future, or you use a different ajax method, or you move away from jQuery, you only have to change the xhr_get definition (being sure to return a promise or at least a done method, in the case of the example above). All the other references throughout the app can remain the same.
There are many more (much cooler) things you can do with $.Deferred, one of which is to use pipe to trigger a failure on an error reported by the server, even when the $.ajax request itself succeeds. For example:
function xhr_get(url) {
return $.ajax({
url: url,
type: 'get',
dataType: 'json'
})
.pipe(function(data) {
return data.responseCode != 200 ?
$.Deferred().reject( data ) :
data;
})
.fail(function(data) {
if ( data.responseCode )
console.log( data.responseCode );
});
}
xhr_get('/index').done(function(data) {
// will not run if json returned from ajax has responseCode other than 200
});
Read more about $.Deferred here: http://api.jquery.com/category/deferred-object/
NOTE: As of jQuery 1.8, pipe has been deprecated in favor of using then in exactly the same way.
If you need async: false in your ajax, you should use success instead of .done. Else you better to use .done.
This is from jQuery official site:
As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done().
From JQuery Documentation
The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). These methods take one or more function arguments that are called when the $.ajax() request terminates. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.) Available Promise methods of the jqXHR object include:
jqXHR.done(function( data, textStatus, jqXHR ) {});
An alternative construct to the success callback option, refer to deferred.done() for implementation details.
jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.
jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { });
(added in jQuery 1.6)
An alternative construct to the complete callback option, the .always() method replaces the deprecated .complete() method.
In response to a successful request, the function's arguments are the same as those of .done(): data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail(): the jqXHR object, textStatus, and errorThrown. Refer to deferred.always() for implementation details.
jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {});
Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details.
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use
jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
It appears there are two ways to construct a success callback for jQuery, one form having 3 parameters and the other having only 1. Which of these is correct, and why do both forms appear?
Look at the success function in the docs: http://api.jquery.com/jquery.ajax/
Function( Anything data, String textStatus, jqXHR jqXHR )
A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object.
So the success function can take 3 parameters: the data returned, the status of the response, and the XHR object. Most of the time, you only need the first parameter.
Maybe you are wondering why these two kind of ajax-using are both working?
$.post(url, callback-when-success);
$.post(url, data-to-be-posted, callback-when-success, server-return-datatype);
Let's have a look on the implementation(source code) of $.post()
jQuery.post = function( url, data, callback, type ) {
/** the trick is right here ! **/
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
In fact, the $.post() always expects four parameter, and if you omit the data-to-be-posted(should be in the 2nd-pos)parameter, and the success-callback is placed on the 2nd-position, then the data would be assigned as undefined and the success-callback would still be the success-callback.
The then and done methods don't care how many parameters your callback has. A jQuery Promise1 can resolve with multiple arguments, and all these arguments will be passed to your callback. Which and how many of them you actually want/need to use is your business.
Some examples:
the animation queue .promise resolves with a single argument, the elements collection.
the $.ready.promise resolves with the jQuery function
the internally used Animation promises resolve with two arguments
the $.ajax promise resolves with the success, statusText, jqXHR arguments
a $.when(promise1, promise2, promise3, …) promise resolves with arbitrarily many arguments
a promise.then(function() { return … }) promise resolves with the single … value
1: Notice that almost all other promise libraries put promises for single values only, see here for example.
I have been working with jQuery and AJAX for a few weeks now and I saw two different ways to 'continue' the script once the call has been made: success: and .done.
From the synopsis from the jQuery documentation we get:
.done(): Description: Add handlers to be called when the Deferred object is resolved.
success: (.ajax() option): A function to be called if the request succeeds.
So, both do something after the AJAX call has been completed/resolved. Can I use one or the other randomly? What is the difference and when one is used instead of the other?
success has been the traditional name of the success callback in jQuery, defined as an option in the ajax call. However, since the implementation of $.Deferreds and more sophisticated callbacks, done is the preferred way to implement success callbacks, as it can be called on any deferred.
For example, success:
$.ajax({
url: '/',
success: function(data) {}
});
For example, done:
$.ajax({url: '/'}).done(function(data) {});
The nice thing about done is that the return value of $.ajax is now a deferred promise that can be bound to anywhere else in your application. So let's say you want to make this ajax call from a few different places. Rather than passing in your success function as an option to the function that makes this ajax call, you can just have the function return $.ajax itself and bind your callbacks with done, fail, then, or whatever. Note that always is a callback that will run whether the request succeeds or fails. done will only be triggered on success.
For example:
function xhr_get(url) {
return $.ajax({
url: url,
type: 'get',
dataType: 'json',
beforeSend: showLoadingImgFn
})
.always(function() {
// remove loading image maybe
})
.fail(function() {
// handle request failures
});
}
xhr_get('/index').done(function(data) {
// do stuff with index data
});
xhr_get('/id').done(function(data) {
// do stuff with id data
});
An important benefit of this in terms of maintainability is that you've wrapped your ajax mechanism in an application-specific function. If you decide you need your $.ajax call to operate differently in the future, or you use a different ajax method, or you move away from jQuery, you only have to change the xhr_get definition (being sure to return a promise or at least a done method, in the case of the example above). All the other references throughout the app can remain the same.
There are many more (much cooler) things you can do with $.Deferred, one of which is to use pipe to trigger a failure on an error reported by the server, even when the $.ajax request itself succeeds. For example:
function xhr_get(url) {
return $.ajax({
url: url,
type: 'get',
dataType: 'json'
})
.pipe(function(data) {
return data.responseCode != 200 ?
$.Deferred().reject( data ) :
data;
})
.fail(function(data) {
if ( data.responseCode )
console.log( data.responseCode );
});
}
xhr_get('/index').done(function(data) {
// will not run if json returned from ajax has responseCode other than 200
});
Read more about $.Deferred here: http://api.jquery.com/category/deferred-object/
NOTE: As of jQuery 1.8, pipe has been deprecated in favor of using then in exactly the same way.
If you need async: false in your ajax, you should use success instead of .done. Else you better to use .done.
This is from jQuery official site:
As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done().
From JQuery Documentation
The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). These methods take one or more function arguments that are called when the $.ajax() request terminates. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.) Available Promise methods of the jqXHR object include:
jqXHR.done(function( data, textStatus, jqXHR ) {});
An alternative construct to the success callback option, refer to deferred.done() for implementation details.
jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.
jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { });
(added in jQuery 1.6)
An alternative construct to the complete callback option, the .always() method replaces the deprecated .complete() method.
In response to a successful request, the function's arguments are the same as those of .done(): data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail(): the jqXHR object, textStatus, and errorThrown. Refer to deferred.always() for implementation details.
jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {});
Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details.
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use
jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
Let's create a simple Deferred object:
defer = $.Deferred( function ( defer ) {
setTimeout( defer.resolve, 3000 );
});
The above Deferred object will be in the "pending" state for 3 seconds, and then switch to the "resolved" state (at which point all the callbacks bound to it will be invoked).
Let's also retrieve the promise of that Deferred object:
promise = defer.promise();
Now, to add callbacks which are going to be invoked once the Deferred object is resolved, we can use .done() or .then(). However, we can invoke this method both on the Deferred object itself or its own promise object.
defer.then( handler );
or
promise.then( handler );
In both cases, the handler function will be invoked (after 3 seconds in this case).
If we use $.when, we can again pass the Deferred object itself or its promise object:
$.when( defer ).then( handler );
or
$.when( promise ).then( handler );
Again, there is no difference between the above two lines of code.
Live demo: http://jsfiddle.net/G6Ad6/
So, my question is since we can invoke .then(), .done(), etc. on the Deferred object itself and since we can pass that Deferred object into $.when(), what's the point of .promise() and retrieving the promise object? What's the purpose of the promise object? Why is there this redundancy in functionality?
It creates a "sealed" copy of the deferred value, without the .resolve() and .reject() methods. From the documentation:
The deferred.promise() method allows an asynchronous function to prevent other code from interfering with the progress or status of its internal request.
It's used when it doesn't make sense for the value to be modified. For example, when jQuery makes an AJAX request it returns a promise object. Internally it .resolve()s a value for the original Deferred object, which the user observes with the promise.
When using the "promise" of a Deferred object the observers (objects waiting for resolve for exemple) dont have direct access to the Deferred object itself, so they can't call, for exemple, the method "Resolve" of that Deferred. It is a way of protecting the original Deferred.
With Deferred, you can control its state set.
When it comes to the Promise, you can read state and maybe attach callback. get
I'm getting an unexpected result when using $.when() when one of the deferred operations does not succeed.
Take this JavaScript, which created 2 deferreds. The first one succeeds and the second one fails.
var f1 = function() {
return $.Deferred(function(dfd) {
dfd.resolve('123 from f1');
}).promise();
};
var f2 = function() {
return $.Deferred(function(dfd) {
dfd.reject('456 from f2');
}).promise();
};
$.when(f1(), f2())
.then(function(f1Val, f2Val) {
alert('success! f1, f2: ' + JSON.stringify([f1Val, f2Val]));
})
.fail(function(f1Val, f2Val) {
alert('fail! f1, f2: ' + JSON.stringify([f1Val, f2Val]));
});
Run it yourself: http://jsfiddle.net/r2d3j/2/
I get fail! f1, f2: ["456 from f2", null]
The problem is that in the .fail() callback the value passed with the f2() rejection, is being routed to the first argument, where i expect the f1Value. Which means that I don't really have a way of know which deferred object actually posted that reject(), and I also dont know which operation that failure data actually belongs to.
I would have expected that .fail() would get arguments null, '456 from f2' since the first deferred did not fail. Or am I just not doing deferreds right way here?
How do I know which deferreds failed, and which rejection arguments belong to which failed deferred if the argument order in the callback is not respected?
$.when() will execute the failed callback (2nd parameter passed to then()) immediately if any one of the parameters fails. It's by design. To quote the documentation:
http://api.jquery.com/jQuery.when/
In the multiple-Deferreds case where one of the Deferreds is rejected, jQuery.when immediately fires the failCallbacks for its master Deferred. Note that some of the Deferreds may still be unresolved at that point. If you need to perform additional processing for this case, such as canceling any unfinished ajax requests, you can keep references to the underlying jqXHR objects in a closure and inspect/cancel them in the failCallback.
There's actually no built-in way of getting a callback that waits untils all of them are finished regardless of their success/failure status.
So, I built a $.whenAll() for you :)
It always waits until all of them resolve, one way or the other:
http://jsfiddle.net/InfinitiesLoop/yQsYK/51/
$.whenAll(a, b, c)
.then( callbackUponAllResolvedOrRejected );
Internally, the "reject" and "fail" paths are handled by two totally separate queues, so it just doesn't work the way you expect.
In order to know which original Deferred failed from the "when()" group, you could have them pass themselves along with the ".reject()" call as part of an object literal or something.
I've faced this same problem, and I dealt with it by using the .always callback and inspecting my array of deferred objects. I had an unknown number of ajax calls, so I had to do the following:
// array of ajax deletes
var deletes = [];
$checkboxes.each(function () {
deletes.push(deleteFile(this));
});
$.when.apply($, deletes)
.always(function () {
// unfortunately .fail shortcircuits and returns the first fail,
// so we have to loop the deferred objects and see what happened.
$.each(deletes, function () {
this.done(function () {
console.log("done");
}).fail(function () {
console.log("fail");
});
});
});
The deleteFile method returns a promise, which has .done or .fail callbacks.
This allows you to take action after all deferreds have completed. In my case I'm going to show a delete file error summary.
I just tried this, and unfortunately I had to put a interval timer to check that they were all truly done after my $.each on the deferred objects. This seems odd and counterintuitive.
Still trying to understand these deferreds!
Very old question but now, to wait until all are resolved, you can use Promise.allSettled since $.ajax deals with standard promises.
The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise
Therefore you can use
Promise.allSettled([$.ajax(), $.ajax()])
.then((res) => {
if (res[0].status === 'fulfilled') {
console.log(res[0].value)
// do something
} else {
console.error('res1 unavailable')
}
if (res[1].status === 'fulfilled') {
console.log(res[1].value)
// do something
} else {
console.error('res2 unavailable')
}
})