This is a sample dynamically updated chart:
http://www.highcharts.com/demo/dynamic-update
The chart is updated every second with the the date as the x value and a random number as the y value.
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);
}
How would I rewrite load to fetch x and y from another webpage using AJAX, rather than generating the values within the function?
I take it what you want is the sample
loadmethod but with the lines that setxandyreplaced with an AJAX call. You’ll need to perform a fairly basic continuation-passing code transformation, turning the code after the point you want the asynchronous call into a function that’s passed to the asynchronous call. “Continuation” simply means “the rest of the calculation, from a given point forward”. In the code sample, that’s the call toseries.addPoint. The pattern for this is you transform:into:
If (2) returned a value in the original function, then the call to
fmust also be rewritten using continuation passing style, adding an extra parameter to hold the continuation.The other thing you should do is make sure the PHP script outputs the numeric pair as valid JSON, either as an array of two numbers (which can be passed directly to the
series.addPointcall after parsing), or as an object with properties “x” and “y”.Note that, due to the nature of network communication, the data may not arrive in a timely manner, resulting in a graph with irregular intervals.
Here’s the gist, wrapping up the nuts-and-bolts of the asynchronous call into a function named
ajaj. The sample assumes the browser supports the necessary standards for XMLHttpRequest and the JSON parser.JS libraries provide their own version of
ajaj, often with more features. If you’re doing anything of any complexity for a production site, look into adopting one. If you’re using jQuery (as the tag suggests), you can, for example, usejQuery.get:The server side of things is dead simple.
time()returns a Unix timestamp,rand()returns a (not very) pseudorandom number (though good enough for a demo), andjson_encode(), well, you can figure that out.