0

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?

2 Answers 2

2

You're probably not waiting for the getJSON function to complete. It's asynchronous which means that code under it will execute before code in the callback function.

alert(1);
$.getJSON("tljson.json",function(result){
  alert(2);
  items = JSON.stringify(result);
});
alert(3);

The example above actually alerts 1 then 3 then 2. Note that the 3 is before the 2.

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 items before 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.

$.getJSON("tljson.json",function(result){
  items = JSON.stringify(result);
  doSomethingWithItems();
});

function doSomethingWithItems() {
  alert(items); // Correctly alerts items.
}
Sign up to request clarification or add additional context in comments.

Comments

1

This is because your code is executing before response from getJSON is received. Use it like:

  function afterGetJSON(items) {
    timeline.draw (items,options);
  }

  $.getJSON("tljson.json",function(result){
    items = JSON.stringify(result);
    afterGetJSON(items);

  });

Comments

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.