0

I'm trying the following to pull in a json formatted file into a JS variable (the json file is correct json).

var data;
$.getJSON('../data/data.js', function(json){
    data = json;
});
console.log(data);

The result is:

undefined

When I console.log inside the $.getJSON function I do get the results.

Any idea what I might be doing wrong?

gvlasov
  • 18,638
  • 21
  • 74
  • 110
Miguel Stevens
  • 8,631
  • 18
  • 66
  • 125
  • 2
    `getJSON` is asynchronous. `data` will be `undefined` when you log it. Add a `console.log()` to the callback function and you'll see that it fires asynchronously, with a delay. – James Feb 25 '15 at 12:49
  • @JayBhatt getScript() also executes the data, but since it's json isn't that a bad idea? – Miguel Stevens Feb 25 '15 at 12:51

1 Answers1

1

The file seems to be received successfully. However, your problem is that the callback function is run asynchronously, so data is value is not defined when it is logged.

Solution:

var processFile = function (fileData) {
    // do processing here.
}


var data;
$.getJSON('../data/data.js', function(json){
    data = json;
    processFile(data);
});
Oday Fraiwan
  • 1,147
  • 1
  • 9
  • 21
  • It's not `null` it's `undefined`. – Joe Feb 25 '15 at 12:55
  • Thank you, But i need to use the data afterwards.. How can I do that? the console.log is just for testing. thanks – Miguel Stevens Feb 25 '15 at 12:57
  • It is not a concern here, the objective is that no value is assigned to data. However, edited the answer. – Oday Fraiwan Feb 25 '15 at 12:58
  • @Notflip you can handle the response in a function where one of the parameters is the data received (the JS file). See updated answer – Oday Fraiwan Feb 25 '15 at 12:59
  • Hmh still not working, I can process the data in the processFile function, but I want to be able to use the data in the whole file.. which is not working, thank you for your time so far! – Miguel Stevens Feb 25 '15 at 13:09