user2052251
user2052251

Reputation: 161

Loading a JSON file with jQuery.getJSON

I am a newbie in JS and I am trying to do something very simple.

I have a JSON file named "data.json" and I want to load it, so, I do this:

$.getJSON("data.json",function(data){
    console.log(data);
});

And then I pass that loaded JSON to a function in library that does this:

$("#example1").handsontable({
    data:data,     //<--- error here
    minRows: 2,
    minCols: 3,
    minSpareRows: 1,
    currentRowClassName: 'currentRow',
    currentColClassName: 'currentCol',
    autoWrapRow: true,
    colHeaders: true
});

$("#example1").handsontable('selectCell', 3, 3);

Firebug says

ReferenceError: data is not defined
[Break On This Error]   

data:data,

I thought I already loaded the JSON into the data variable? Any suggestions?

Upvotes: 2

Views: 316

Answers (1)

Mark Reed
Mark Reed

Reputation: 95395

data is only defined inside the callback you pass to getJSON. Whatever you're ever going to do with that has to be done within that function.

So instead of (or in addition to) the console.log(data), you need to do the handsontable call (or call a function that does the handsontable call) right there in the getJSON callback.

Also, getJSON is asynchronous, which means even if you do something like assign data to a global variable inside the callback, that variable probably won't have that value yet when you get to the next line of code after the getJSON call. All you've done is issued a request - "hey, go get this JSON object, and when you finish doing that, call this function. Meanwhile, I'm going to go on about my business. Thanks!"

Upvotes: 3

Related Questions