How to use AJAX to update charts

A guide for using AJAX to update your charts. AJAX updating can be quicker than refreshing the entire page and can utilise less bandwidth.

[No canvas support]

To update your charts using AJAX requires you to understand that the page you're requesting via AJAX doesn't generate the chart. It only returns the data. Another HTML page (eg the one you're currently reading) takes that data and uses it to generate the chart. The sequence of events is:

  1. The requested HTML page loads in the browser.
  2. That page then makes an AJAX request to get new data
  3. The AJAX request returns the data as text
  4. The original page then parses that text into a usable format (ie an array) and produces the chart

  5. Instead of the points 3 and 4 - you can use the new (April 2013) AJAX functions such as RGraph.AJAX.getCSV() or RGraph.AJAX.getJSON(). These return you appropriate data-types (such as an array or a JavaScript object) and not just strings

The AJAX functions

The RGraph AJAX functions that can be used to make the requests are part of the RGraph common library and you can use them like this. To help prevent giving strings to RGraph when you should be giving numbers or arrays, the new helper functions that change the response into the correct format are:

    // This example callback function simply prints the result of the AJAX call.
    function myCallback (result)

    RGraph.AJAX(url, myCallback);
    RGraph.AJAX.getString(url, myCallback);
    RGraph.AJAX.getNumber(url, myCallback);
    RGraph.AJAX.getCSV(url, myCallback);
    RGraph.AJAX.getJSON(url, myCallback);

    // The function allows you to make POST requests to your server - sending data along with it. The
    // data argument should be an object with key/value pairs eg. {'name': 'Richard Hargreaves','age': 22}
    // The data is encoded for you using encodeURIComponent(), data, callback);

The server-side script

For this example the server side script is just a basic PHP script which generates a sequence of 10 random numbers.

    $data = array();

    for ($i=0; $i<10; ++$i) {
        $data[] = mt_rand(0, 99);
    echo implode(',', $data);
This will output a string of numbers like this:
Remember that because it's being requested as an AJAX request it doesn't need to contain any HTML. The RGraph.AJAX.getCSV() function will take the CSV data and split it up into a usable array of numbers. Keep in mind that it doesn't need to be XML that you return. As shown here it can just be a comma separated sequence of numbers. Indeed if it is XML it makes parsing the result more complex.

The window.onload function

To initiate the creation of the chart the window.onload function makes an AJAX call to the server side PHP script to get the data (which is random in this case, but it could equally be something significant to you).

    window.onload = function (e)
        RGraph.AJAX.getCSV('/getdata.html', myCallback);

The AJAX callback function

This is the function which is called when data is returned by the AJAX call. Because the getCSV() function was used the function is passed an array consisting of the CSV data (which is numbers). You can see this if you were to use the $p() function (p for print) inside the callback.

    // This is the AJAX callback function. When the AJAX function receives the
    // data it calls this function. It then creates the chart.
    function myCallback (data)
        // Start by resetting the canvas. Note that this also resets the anti-aliasing fix - but as the chart is being
        // recreated entirely each call - this is OK.

        // Create the chart
        var myChart = new RGraph.Line({
            id: 'cvs',
            data: data,
            options: {
                yaxisScaleMax: 10,
                marginInner: 10,
                linewidth: 2,
                tickmarksStyle: 'endcircle',
                xaxisLabels: ['Hoolio','Richard','Jack','Kenny','Ivan','Pete','Rodrigo','Luis','Fred','John'],
                textSize: 14

Timed AJAX calls

If you wanted a continually updating chart similar to the one shown above, you could put in a setTimeout() call that refreshes the data every 2 seconds.

window.onload = function (e)
    RGraph.AJAX.getCSV('/getdata.html', myCallback);

    setTimeout(window.onload, 2000); // 2000 milliseconds = 2 seconds

Remember: Don't forget to clear or reset the canvas before you draw on it again.

Making AJAX POST requests

There is now (May 2013) an function that allows you to make POST requests. This function allows you send data along with the request which will be available to server-side scripts as any other post data is. In PHP this means you'll find it in the $_POST variable. The data is encoded for you so you don't need to worry about this.

You can also use jQuery to make AJAX POST requests (or any AJAX requests).