How to use AJAX to update your charts

Share RGraph:   

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

[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:

<script>

    /**
    * This example callback simple prints the result of the AJAX call.
    */
    function myCallback (result)
    {
        p(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 POST 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()
    RGraph.AJAX.POST(url, data, callback);
</script>

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.

<?php
    $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:
5,45,23,56,86,48,45,48,31,21
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 seperated 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).

<script>
    window.onload = function (e)
    {
        RGraph.AJAX.getCSV('/getdata.html', myCallback);
    }
</script>

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 meaning print) inside the callback.

<script>
    /**
    * This is the AJAX callback. When the AJAX function receives the data it calls this function.
    * This function then creates the chart.
    */
    function myCallback (data)
    {
        /**
        * Start by resetting the canvas. Note that this also resets the antialiasing fix - but as the chart is being
        * recreated entirely each call - this is OK.
        */
        RGraph.reset(document.getElementById('cvs'));


        /**
        * Create the chart
        */
        var myChart = new RGraph.Line({
            id: 'cvs',
            data: data,
            options: {
                ymax: 10,
                hmargin: 10,
                linewidth: 2,
                tickmarks: 'endcircle',
                labels: ['Hoolio','Richard','Jack','Kenny','Ivan','Pete','Rodrigo','Luis','Fred','John'],
                textAccessible: true,
                textSize: 14
            }
        }).draw();
    }
</script>

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 AJAX POST 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).

Comments

Add a new comment...