Reputation: 410
Using a Float Charts jquery tool the data var value is like that
var d2 = [[0,0],[1,0],[2,0],[3,0],[4,"1"],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0],[11,0]]
When i change it to be got from a Request using that $.getJSON
var d2 = var d2 = $.getJSON( "UpdateCharts", function() { ......
The Response return as
[[0,0],[1,0],[2,0],[3,0],[4,"1"],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0],[11,0]]
But i got an error that d2 value is 0 and not like first value
Uncaught TypeError: Cannot read property '0' of undefined
Upvotes: 0
Views: 119
Reputation: 7269
Try this (THIS WORKS):
var d2;
$.getJSON( "path/to/json/file", function(data) {
// parse data to the d2
// d2 = data; // <-- use this if you want same array/object structure like json file contents has
console.log(d2); // <-- this will output correct d2 contents
}
Instead of this (EXAMPLE HOW NOT TO DO):
var d2 = $.getJSON( "path/to/json/file", function(data) {
// parse data to the d2
}
console.log(d2); // <-- this will show error/wrong contents, because it is shown before json data was parsed
Error appears, because getJSON is async function. You just define actions which will be done, when something will happen. With getJSON you define actions will be done, when data would be loaded from external storage. You can output data exactly in the function specified in parameter, but not after.
Example:
1. // this part is executing first, order: 1
2. var xxx = $.getJSON( "xxx", function(xxx) { // you just specified what to do when data will be parsed there
3. // this part will be called after all contents will be loaded, order: 3
4. }
5. // this part is executing right after 1st lane, order: 2
Upvotes: 1