I have the following:
$.ajax(link.href,
{
cache: false,
dataType: 'html'
})
.done(onDialogDone)
.fail(onDialogFail);
This works fine and onDialogDone is called. However what arguments should I expect to see supplied to the onDialogDone and what should I expect to see for onDialogFail.
The reason I am asking is because I use typescript and I want to supply the correct arguments when I define my onDialogDone and onDialogFail.
The arguments for .done() and .fail() are the same as the arguments for the corresponding success: and error: parameters for the $.ajax() function, namely:
.done( function(data, textStatus, jqXHR) { ... } );
and
.fail( function(jqXHR, textStatus, errorThrown) { ... } );
For the purposes of typescript, textStatus and errorThrown are strings, jqXHR is an Object, and data depends on what the remote server sends you.
The three parameters passed to the done handler are:
data, textStatus, jqXHR
You can read more here: http://api.jquery.com/jQuery.ajax/
data is the response message
textStatus will always be success in the done function
jqXHR is the raw XMLHttpRequest
Check this out:
Methods (part of jqXHR and Deferred implementations, shown here for clarity only)
.ajax().always(function(a, textStatus, b){});
Replaces method .complete() which was deprecated in jQuery 1.8.
In response to successful transaction, arguments are same as .done() (ie. a = data, b = jqXHR) and for failed transactions the arguments are same as .fail() (ie. a = jqXHR, b = errorThrown).
This is an alternative construct for the complete callback function above. Refer to deferred.always() for implementation details.
.ajax().done(function(data, textStatus, jqXHR){});
Replaces method .success() which was deprecated in jQuery 1.8.
This is an alternative construct for the success callback function above. Refer to deferred.done() for implementation details.
.ajax().fail(function(jqXHR, textStatus, errorThrown){});
Replaces method .error() which was deprecated in jQuery 1.8.
This is an alternative construct for the complete callback function above. Refer to deferred.fail() for implementation details.
.ajax().then(function(data, textStatus, jqXHR){}, function(jqXHR, textStatus, errorThrown){});
Incorporates the functionality of .done() and .fail() methods.
Refer to deferred.then() for implementation details.
.ajax().pipe(function(data, textStatus, jqXHR){}, function(jqXHR, textStatus, errorThrown){});
Incorporates the functionality of .done() and .fail() methods, allowing the underlying Promise to be manipulated.
Refer to deferred.pipe() for implementation details.
Related
So in our code base we are using jquery just for the ajax section of the codebase but we want to wrap all of our calls so if we wanted to eventually get rid of jquery then we would only have to change the implementation. Here is the definition of the wrapper.
export const getAll = (...ajaxCalls) => {
// return $.when($.ajax(ajaxCalls));
return $.when(ajaxCalls.map(call => $.ajax(call)));
}
And here is the where we are calling it.
getAll(`/response/${customerId}`, `/response/${methods}`).done((response1, response2) => {
console.log("getAll1",response1);
console.log("getAll2",response2);
})
However the response is looking something like this:
My understanding of when would be that response1 should contain the responseBody of response1 and response2 should contain the responseBody of response2 but that doesnt seem to be the case. What am I missing?
It seems that you are logging jqHXR objects, which are probably a consequence the odd way that jQuery.ajax() and jQuery.when() interact to deliver results see last but one example here.
In anticipation of purging jQuery at a later stage, I venture to suggest that you need to standardize all your calls at this stage. This is fairly simple, just use .then() instead of .done() and expect results to be delivered in an Array:
getAll(`/response/${customerId}`, `/response/${methods}`)
.then(results => {
console.log("getAll0", results[0]);
console.log("getAll1", results[1]);
});
You then need to jump through a few hoops in getAll() in order to standardize various aspects of jQuery.ajax() and jQuery.when() behaviour:
standardize jQuery.when()'s delivery results as individual parameters rather than Array.
standardize jQuery.ajax()'s delivery of (data, statusText, jqXHR) to its success path.
standardize jQuery.ajax()'s delivery of (jqXHR, statusText, errorThrown) to its error path.
standardize the behaviour of jQuery.ajax()'s error handler across different versions of jQuery.
export const getAll = (...ajaxCalls) => {
function makeAjaxCallAndStandardizeResponse(call) {
return $.ajax(call)
.then(
// success handler: standardize success params
(data, statusText, jqXHR) => data, // discard statusText and jqXHR
// error handler: standardize error params and ensure the error does not remain "caught".
(jqXHR, textStatus, errorThrown) => $.Deferred().reject(new Error(textStatus || errorThrown)).promise(); // discard jqXHR, and deliver Error object on the error path.
);
}
// Aggregate with Promise.all() instead of jQuery.when() to cause a javascript Promise to be returned and results to be delivered as Array.
return Promise.all(ajaxCalls.map(makeAjaxCallAndStandardizeResponse));
}
The success handler is probably unnecessary as the Promise.all() aggregation would automatically cause statusText and jqXHR to be discarded, but no real harm in making those discards explicit, unless you need to be obsessive about milliseconds.
Returning $.Deferred().reject(new Error(textStatus || errorThrown)).promise() from the error handler should give the same behaviour in all versions of jQuery, causing an Error object to be delivered on the error path. (Logged error messages will differ though) Be sure to test this.
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.
Where in the JQuery Docs are these parameters?
jqXHR.done(function( data, textStatus, jqXHR ) {});
http://api.jquery.com/deferred.done/
For example, I tried searching what data would be and cannot find it.
Also, I see examples like .done( function( msg ){} ) or
// Create a deferred object
var dfd = $.Deferred();
// Add handlers to be called when dfd is resolved
dfd
// .done() can take any number of functions or arrays of functions
.done( [ fn1, fn2 ], fn3, [ fn2, fn1 ] )
// We can chain done methods, too
.done(function( n ) {
$( "p" ).append( n + " we're done." );
});
So I am clearly confused about how the parameters are passed to this function.
I need to get the responseText I think, I am echoing a number in PHP.
Thanks!
From jQuery .ajax()
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; a string describing the status;
and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object.
You want the data; that's your server response.
.done is the same as the success callback in your JQuery.ajax properties. The callback is described here: as follows:
http://api.jquery.com/jQuery.ajax/
success
Type: Function( PlainObject data, String textStatus, jqXHR jqXHR )
.done takes 1-n functions or arrays of functions which should get invoked on success of your ajax call
data is simply the data you receive as response from the server, some json object...
When you register a callback with a promise's .done() method, this callback will be passed the parameter that this promise will be resolved with: promise.resolve(data). In the case of a jQuery Ajax request, the servers response body is the data that the XHR promise is resolved with.