0

Is it possible somehow that I can use this data variable outside the $.getJSON call?

var data;

$.getJSON('json/data.json', function(externaldata) {
  data = externaldata;

});
Ognjen
  • 85
  • 1
  • 2
  • 9
  • 1
    No, data won't be there until the inner function runs. You'll need to fire a callback when data is populated. – Dave Chen Mar 10 '16 at 18:20
  • What Dave says is correct. The JSON call is run asynchronously, so any code that depends on the data must be run _after_ the JSON request completes. – Makaze Mar 10 '16 at 18:22
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Teemu Mar 10 '16 at 18:24
  • 1
    yes, it's available outside, but you care more about _when_ than _where_ it's available... – dandavis Mar 10 '16 at 18:38
  • to your simple question the straight answer is yes with the the twist that it will be available only after the external data is loaded completely. Else it will hold the initial/old data. For that you can keep a callback inside getJSON callback function or set a flag there which you can check for while using data variable. – Kishore Barik Mar 10 '16 at 18:47

2 Answers2

1

this is a great chance to review the asynchronous nature of JavaScript. We've all been caught here, believe me. I get reminded with every file read/write or every time I get data from an other source.

First off, you are using a jQuery function, getJSON. Look at the details for how that function works, click here.

The form is jQuery.getJSON( url [, data ] [, success ] ) In that form, data is information being sent TO the server. You need to declare a success handler. There are some really good samples on how to use that call on the jQuery reference page.

var data;

$.getJSON('json/data.json', function(externaldata) {
  //data = externaldata;
  useJSONdata(externaldata);

});

function useJSONdata(rawData, callback){
// do stuff with data here...
callback();
}

or

$.getJSON('json/data.json', useJSONdata(externaldata) {
}
zipzit
  • 3,778
  • 4
  • 35
  • 63
0

You can anywhere assign value to a global variable in javascript and it will be available throughout the webpage.

Abhishek Dhanraj Shahdeo
  • 1,356
  • 2
  • 14
  • 35
  • after the getJSON call I can only view what's in the data variable inside that function , I cannot use it outside of it. – Ognjen Mar 10 '16 at 18:20