Dave Wicomo
Dave Wicomo

Reputation: 163

How to get data from Json

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);

Upvotes: 1

Views: 149

Answers (2)

Naresh Pingale
Naresh Pingale

Reputation: 246

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)
});

Upvotes: 1

Shyju
Shyju

Reputation: 218702

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.

Upvotes: 0

Related Questions