Miguel Stevens
Miguel Stevens

Reputation: 9220

Javascript .js file to variable

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?

Upvotes: 0

Views: 59

Answers (1)

Oday Fraiwan
Oday Fraiwan

Reputation: 1157

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

Upvotes: 1

Related Questions