matthew kap matthew kap - 3 years ago 119
Javascript Question

How to extract and display data from an API?

I'm trying to download and display the API data from a website. Here's the code I'm currently using:

function loadJSON(file, callback) {

var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', file, true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
}
var outerSpace;
loadJSON("http://api.open-notify.org/astros.json", gotData);

function gotData(data) {
outerSpace = data;
}

if (outerSpace) {
console.log(outerSpace.people.name);
}


This is the full API ( not much ).

{
"number": 3,
"message": "success",
"people": [
{
"name": "Peggy Whitson",
"craft": "ISS"
},
{
"name": "Fyodor Yurchikhin",
"craft": "ISS"
},
{
"name": "Jack Fischer",
"craft": "ISS"
}
]
}


Shouldn't console.log output "Peggy Whitson"? I get no error messages but the console receives no messages. If anyone could help me find a fix I'd greatly appreciate it. Thank you!

Answer Source

I think the other answers are well and good, I just wanted to point out where I think the misunderstanding lies:

  // Here you create the callback.
  // It will run later when the ajax-call completes.
  function gotData(data) {
    outerSpace = data;
  }

  // This however runs immediately and only once.
  // outerSpace will *always* be undefined at this point 
  // Because gotData has not yet completed. 
  // (The whole thing about ajax-calls are that they complete *later*.)
  if (outerSpace) {
    console.log(outerSpace.people.name);
  }

You treat if as if it could mean when (sadly there is no such thing) All you have is your callback, so you have to put your logic there:.

  function gotData(data) {
    outerSpace = data;
    if (outerSpace) {
      console.log(outerSpace.people.name);
    }
  }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download