Cannot get the responseText out of Ajax request - javascript

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!

Related

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.

Understanding JQuery Docs on $.Ajax

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.

AJAX Promises using Array

I'm trying to make several AJAX calls (let's say 2) using promises. Basically I want to be able to merge the two responses together, perform some analysis on them as a whole, then spit out a response.
Right now, I have:
var responseArray = [];
for (var i=0; i<letsSayTwo; i++) {
responseArray.push(someAjaxCall(data));
};
responseArray.done(function(response) {
var spit = someAnalysis(response);
console.log(spit);
});
responseArray.fail(function(response) {
console.log('fail');
});
As it stands, I'm getting an "Uncaught TypeError: Object [object Array] has no method 'done'" error in console. Am I correct in thinking that I can't use this method? I looked into using the following bit of code from (http://gregfranko.com/blog/jquery-best-practices/) but I can't seem to get the response that I need.
$.when.apply(this, responseArray).then(function(response) {
console.log(response);
});
Instead, what I get is [response, "success", response] where the first response is the correct return response for one of the AJAX calls and the last response is the actual call itself. How should I go about getting the correct responses from both AJAX calls??
I hope this all makes sense. Thanks!
As it stands, I'm getting an Uncaught TypeError: Object [object Array] has no method 'done' error in console. Am I correct in thinking that I can't use this method?
Not on arrays, yes. You can call this method only on Promise and Deferred objects, like the one produced by $.when.apply(this, responseArray)
… but I can't seem to get the response that I need. Instead, what I get is [response, "success", response] where the first response is the correct return response for one of the AJAX calls and the last response is the actual call itself.
As stated in the docs for $.when, it resolves the result promise with multiple arguments - and when the input promises themselves did yield multiple values (such as $.ajax does), each argument is an arguments object of the respective promise resolution. You were only getting the first of them with response, but there are responseArray.length (letsSayTwo) arguments to the callback.
How should I go about getting the correct responses from both AJAX calls?
You want to extract the first item (response data) from each arguments object, so you can use map:
$.when.apply(this, responseArray).done(function() {
var responses = $.map(arguments, function(args) { return args[0]; }),
spit = someAnalysis(responses);
console.log(spit);
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log('fail: '+textStatus);
});

How can Ajax do asynchronous request and response a synchronous result

I find a fantastic bug when I use jQuery ajax to do a request to web service:
var AjaxResult;
login = function () {
AjaxResult = "";
$.ajax({
type: "POST",
url: KnutBase.getServiceUrl() + "ServiceInterface/HmsPlannerWebService.asmx/AuthenticateLogin",
data: { username: this.username, password: this.password },
dataType: 'jsonp',
success: function (response) {
//the response value is 'success'
AjaxResult = response;
},
error: function (data, status, e) {
alert("error:" + e);
}
});
//alert(AjaxResult);
//if i do not alert a message here, this function will return a null value
//however, i do alert here, then i get a 'success' value.
return AjaxResult;
}
How could this happen.
I am confused as to why the AjaxResult returns its value before the ajax method set response value to it.
Ajax is asynchronous call to your method and it do the processing in the back for server trip. You will not get the result until the success method is called. You can read more about jquery ajax here
You can set async attribute to false of ajax() to make a synchronous call.
EDIT: Using deferreds --
$.Deferred can be used to run code after some other code has completed. Ajax is an excellent example, and all of the jQuery ajax methods (except .load) implement the $.Deferred interface. You can use $.when to watch deferreds. For example:
login = function () {
return $.ajax({...
The deferred gets returned from the method above, so you can do the following:
$.when(login()).done(function (response) { ... });
Any code that needs to be synchronized with the ajax response has to go in the .done callback.
Note that this is not much different than just using the success callback with $.ajax. The point is that all of your work that relies on what is returned from Ajax needs to be done in these callbacks.
Since ajax is asynchronous, return AjaxResult is actually executed before the ajax result completes. You can not return in this way; you need to perform some action in the callback of the ajax requests or use deferred.
It has to do with the fact that AJAX is asynchronous (that's actually the meaning of the first A in it). alert stops the code until you press the button, and the request has time to complete. With no alert, the function proceeds immediately, the AJAX has barely begun its work, and of course the value is still empty.
Generally, you can't have functions return values that they get from AJAX. Set up a callback for it, and deal with it when it comes.
How can Ajax do asynchronous request and return a synchronous result
You can't. It's just impossible. If your code really tries to do that, it will fail.

Modifying JSONP results before success callback

I'd like to load some JSON data from an external service. However, it provides
{ foo: ..., bar: ..., useful: {...} }
and what I really care about is in the "useful" part. I need to pass just that part to the success callback.
I'm trying to use Deferred to load from multiple data sources at once -- something like this. I'd like to retrieve the data, "massage" the result, and have just the "useful" part in the example above actually passed to the then callback. My understanding is that when you pass a Deferred to when(), the data goes directly to the callback passed to then(), so I need to hook into the process before it gets there.
I tried dataFilter but for JSONP that's not possible. Is there any other way to intercept these results? I can add some checks to my then() callback to handle cached data differently from the "fresh" results, but that sort of loses the magic of Deferred in the first place.
To clarify, this doesn't work:
$.when($.ajax({
url: "host/service",
dataType: "jsonp",
dataFilter: function(data, type){
return data.useful; // throws, data === undefined
}
})).then(function(usefulStuff){ ... });
You can call .pipe() to process the data and create a new Deferred:
$.getJSON(...).pipe(function(results) {
return ...;
})

Categories