2

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?

3
  • Why do you have a data:data? Remove it and I think it will work. Commented Feb 19, 2013 at 23:01
  • 1
    I don't see where you are doing anything other than logging the data received by getJSON request. Commented Feb 19, 2013 at 23:03
  • possible duplicate of How to return the response from an AJAX call from a function? Commented Feb 19, 2013 at 23:16

1 Answer 1

3

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!"

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for responding.. Is there a way to just read the json data from a file and assign it to a variable. But thanks for pointing that out
Alternatively assign data to a variable with scope outside the callback. Either way, it has to be done inside that callback.
@kinakuta- but if you do that, then you still have to make sure that whatever uses that variable doesn't get triggered until the callback has been . . . called . . . back.

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.