Understanding JQuery Docs on $.Ajax - javascript

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.

Related

Difference between a jQuery's .done(function() {}) and a success callback? [duplicate]

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.

Why does the jQuery success callback sometimes have 3 parameters and sometimes have only 1?

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.

Differences in jQuery's callback approaches [duplicate]

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.

Understanding jquery's done/fail/always under the hood

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/

Cannot get the responseText out of Ajax request

I am making an ajax call and getting an Object in the response.
When i try and get responseText, it tells me it is undefined:
var results = API.get('users', { username: un, userpass: pw } );
console.log(results); //the object response below
console.log(results.responseText); // returns undefined
The Object looks like (I deleted useless parts of the response):
Object {readyState: 1, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
responseJSON: Object
responseText: "{"orderBy":"","orderDesc":false,"rows":[{"id":"26","name":"Jordan Simon","username":"jordan","userpass":"jordan"}],"totalResults":1,"totalPages":1,"pageSize":1,"currentPage":1}"
statusText: "OK"
__proto__: Object
What am I doing wrong? Could you give an example?
You have the answer in comments but here's a complete explanation on what's going on:
API.get is making an asynchronous call to some server, which may, or may not return a respone at some time in the future. While console.log(results) is executed right after the API.get call is but before the response is returned.
Most AJAX calls allow you to specify a callback function that will get executed as soon as the async operation is completed.
For example in jQuery:
$.get( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
});
The method looks somewhat like this:
$.get(url, callback) {
//do some stuff here with the URL
//get the response text, get the XHR response, anything goes really
//execute the callback method passed by the user
callback(responseText);
//return XHR response
return ajaxResults;
}
Notice how the second parameter in the $.get method is a function. This is the basic of async AJAX calls.
Your API might be different, maybe you have an event you need to register for, maybe you can turn off async for whatever purpose. Check out your API's documentation and good luck!

Categories