1

I' currently learning AJAX technology.

In Chrome console when I type jsonObject.responseText, I get all data in the console, but when I do the same in my .js file to print that to the console (or HTML element) it says "undefined" in the console.

JSON object is from:

https://jsonplaceholder.typicode.com/users

Code in JavaScript:

var jsonObject = $.ajax({
url: "https://jsonplaceholder.typicode.com/users",
dataType: "json"
});
console.log(jsonObject.responseText);
Obsidian Age
  • 41,205
  • 10
  • 48
  • 71
Dave Wicomo
  • 163
  • 1
  • 1
  • 12
  • AJAX is, as per its own definition, **asynchronous** in nature. You should check for the resolution of the promise returned by `jsonObject`., i.e. `jsonObject.done(function(response) {...});` – Terry Sep 17 '17 at 21:01
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Terry Sep 17 '17 at 21:02

2 Answers2

1

AJAX - Asynchronous JavaScript and XML. Which means the data is fetched asynchronously in a separate thread.

var jsonObject = $.ajax({ url: "https://jsonplaceholder.typicode.com/users", dataType: "json" });

console.log(jsonObject.responseText);

your console.log is executed before the $.ajax is actually completed getting data. Thus jsonObject is undefined. By the time you execute same in console $.ajax is complete and now at this point the data is present inside jsonObject unlike before.

You will need to provide a success callback which executes when the response is returned.

var jsonObject = $.ajax({ 
    url: "https://jsonplaceholder.typicode.com/users", 
    dataType: "json"
}).done(function(res) {
    console.log(res)
});
Naresh Pingale
  • 246
  • 1
  • 6
0

You should access the response you are getting from the ajax call inside the success /done handler of the call.

$.ajax({
    url: "https://jsonplaceholder.typicode.com/users",
    dataType: "json"
    })
    .done(function(jsonObject){
       // Received response from the call. Now you can safely access it
       console.log(jsonObject);
   });

Here is a working jsbin

Callbacks specified in the done handler will be executed when the ajax call successfully receives a response from the server.

Shyju
  • 214,206
  • 104
  • 411
  • 497
  • 1
    `jqXHR.success()` has been deprecated since jQuery v1.8. Use `jqXHR.done()` instead. – Terry Sep 17 '17 at 21:01
  • and 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. – Shyju Sep 17 '17 at 21:12