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;
});
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;
});
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) {
}
You can anywhere assign value to a global variable in javascript and it will be available throughout the webpage.