I have an issue in that the $.getJSON segment of code works fine and produces a variable called 'zippy'. I need to access 'zippy' under 'series: data' further down in the code.
I have tried a number of things unfortunately i can't make it work. The easiest would be way to 'return data' $.getJSON(jsonUrl,function(zippy) out of the funcation(zippy) call but I'm lost as to how to make that data available.
$(function() {
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
console.log("+++++++++++++++++++++++++++++++++++++");
var jsonUrl = "http://www.someurl.com/thing.php?callback=?";
$.getJSON(jsonUrl, function(zippy) {
for(i = 0; i < zippy.cpmdata.length; i++) {
console.log("TIMESTAMP: " + zippy.cpmdata[i].timestamp + " AFTER: ");
zippy.cpmdata[i].timestamp = Date.parse(zippy.cpmdata[i].timestamp).getTime() / 1000;
//var unixtime Date.parse(temptime).getTime()/1000
console.log(" TESST " + zippy.cpmdata[i].timestamp + " \r\n");
}
});
console.log("+++++++++++++++++++++++++++++++++++++");
var chart;
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'spline',
marginRight: 10,
events: {
load: function() {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function() {
var x = (new Date()).getTime(), // current time
y = Math.random();
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
series: [{
name: 'Random data',
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
console.log("++NEED ACCESS HERE FOR ZIPPY++");
console.log(" =============== \r\n");
console.log(" FINAL " + zippy.cpmdata[5].timestamp + " \r\n");
return data;
})()
}]
}
Your problem is that getJSON is asynchronous. What's happening in your code is this:
You try to draw a chart using HighCharts
... several hundred milliseconds later
The browser makes the JSON request
... several hundred milliseconds later
The JSON request returns with data and triggers the callback to "function(zippy)"
So you see. The problem is not how "function(zippy)" is executed but when it is executed. As such, you cannot execute code that wants to use the return value of the JSON request outside of the callback function. (Actually you can but we'll ignore polling with setTimeout or using synchronous ajax for now)
The solution is to move all the code that you want to run later on inside the callback function:
You need to put all of the
new Highcharts.Chart({...})
stuff inside thegetJSON
callback, because you need to wait until the json request completes before creating the chart. See my code comment that saysCUT AND PASTE chart = new Highcharts.Chart({...}) STUFF HERE!!!
.