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?

2
  • 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. Commented Feb 25, 2015 at 12:49
  • @JayBhatt getScript() also executes the data, but since it's json isn't that a bad idea? Commented Feb 25, 2015 at 12:51

1 Answer 1

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);
});
Sign up to request clarification or add additional context in comments.

5 Comments

It's not null it's undefined.
Thank you, But i need to use the data afterwards.. How can I do that? the console.log is just for testing. thanks
It is not a concern here, the objective is that no value is assigned to data. However, edited the answer.
@Notflip you can handle the response in a function where one of the parameters is the data received (the JS file). See updated answer
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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.