0

I'm currently trying to load my JSON file into my JavaScript file.

I did a lot of research on trying to understand what I should be doing and how I should get it to work, but I can't get it to properly load into a variable.

This is the contents of my JSON file:

[
  {
    "id": 0,
    "name": "Valley of Trials",
    "desc": "Hello world",
    "choices": []
  },
  {
    "id": 1,
    "name": "Valley of Trials",
    "desc": "",
    "choices": []
  }
]

I'm loading and calling it like this:

var jsonLocations;
$.getJSON("../html/data.json", callbackFuncWithData);

function callbackFuncWithData(data) {
    jsonLocations = data;
}

console.log(jsonLocations[0].name);

I read in a question on this site that it needed to be loaded this way otherwise the variable wouldn't be assigned the data due to the asynchronous calling. However, on opening the file in firefox (with firebug), I get an error saying: TypeError: jsonLocations is undefined.

However, in the watch list in firebug it gives me a rundown of all my variables, and I can open up jsonLocations and it will show me a tree hierarchy with the array, the objects and the properties.

So why is it that I'm getting this error? Surely if firebug is showing that jsonLocations has loaded my data it should be displayed in the console.log statement?

Please let me know what is wrong with my code.

Thanks, Joeb.

Joeb Rogers
  • 348
  • 1
  • 2
  • 14
  • 2
    Since the call is asynchronous the `callbackFuncWithData` method will not happen until after the `console.log` has happened. Try moving `console.log` into the `callbackFuncWithData` and see if the object is populated. – Will P. Oct 02 '15 at 21:10

1 Answers1

2

In your code, the line console.log(jsonLocations[0].name); is executed immediately after $.getJSON is fired. It does not wait until the AJAX request is actually complete.

To ensure you log it after the data is fetched, you need to move it inside the callback function:

var jsonLocations;
$.getJSON("../html/data.json", function callbackFuncWithData(data) {
    jsonLocations = data;
    console.log(jsonLocations[0].name);
});
Ananth
  • 4,227
  • 2
  • 20
  • 26
  • Thanks, I suppose I misunderstood the logic behind the callback function. In reality, there are about 170 lines of code between the $.getJSON and the console.log, with many lines of code being called, so I thought that would solve the issue. Is there any way to do this without putting it inside the callback? – Joeb Rogers Oct 02 '15 at 21:39
  • The `$.getJSON` method is asynchronous, there is no way if use this method. You can use `$.ajax()` ( http://stackoverflow.com/a/1457704/1023432 ) method and pass `async: false` in options to make the event queue wait until ajax request returns a result. But do read on why it is not recommended. – Ananth Oct 03 '15 at 20:02