I’m trying to assign a JSON array to a variable as follows:
$.getJSON("tljson.json",function(result){
items = JSON.stringify(result);
});
And then calling that variable outside the function:
timeline.draw (items,options);
Using alert (items) inside the getJSON function works, however, outside of the function, it just returns ‘undefined’. I thought this would work, as I declared items as a global variable in the getJSON function. What am I doing wrong?
You’re probably not waiting for the
getJSONfunction to complete. It’s asynchronous which means that code under it will execute before code in the callback function.The example above actually alerts
1then3then2. Note that the3is before the2.In order to fix your code, you’ll need to wait until the callback function is called so that it can assign a value to
itemsbefore you try to use that variable. Coming up with a solution may depend on your situation, but an easy idea is to call some function from within your callback.