0

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?

Jordan Simon
  • 289
  • 1
  • 4
  • 14
  • Could you try this: `console.log(JSON.stringify(results));` and paste the results from the console? – Darin Dimitrov Oct 10 '13 at 13:54
  • Welcome to the wonderful world of **async**! You can't do that. – SLaks Oct 10 '13 at 13:57
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Ram Oct 10 '13 at 14:01

1 Answers1

1

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!

Mataniko
  • 2,212
  • 16
  • 18