HOWTO: Use AJAX to update your charts

[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 this one) 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 call to get new data
  3. The AJAX page returns the data as text
  4. The original page then parses that text into a usable format (ie an array) and produces the chart

1. The AJAX function

This is the AJAX function that is used to get the new data. It's given the URL to fetch and a callback function that can handle the new data.

<script>
    /**
    * Makes an AJAX call. It calls the given callback (a function) when ready
    * 
    * @param string   url      The URL to retrieve
    * @param function callback A function that is called when the response is ready, there's an example below
    *                          called "myCallback".
    */
    function AjaxCall (url, callback)
    {
        // Mozilla, Safari, ...
        if (window.XMLHttpRequest) {
            var httpRequest = new XMLHttpRequest();
        
        // MSIE
        } else if (window.ActiveXObject) {
            var httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        }
        
        httpRequest.onreadystatechange = callback;
        
        httpRequest.open('GET', url, true);
        httpRequest.send();
    }
</script>

2. 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);
?>

3. 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)
    {
        AjaxCall('http://' + location.host + '/getdata.html', myCallback);
    }
</script>

4. The AJAX callback function

This is the function which is called when data is returned by the AJAX call. It takes the data, splits it into an array, converts that array from an array of strings into an array of numbers and then generates the chart.

<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 ()
    {
        // Check the readystate to see if the XMLHttpRequest object is ready
        if (this.readyState == 4 && this.status == 200) {
            
            var data = this.responseText.split(',');
            
            /**
            * IMPORTANT: Must convert the data (which is a string) to numbers
            */
            for (var i=0; i<data.length; ++i) {
                data[i] = Number(data[i]);
            }
            
            /**
            * Create the chart
            */
            var myChart = new RGraph.Line('cvs', data);
            myChart.Set('chart.ymax', 100);
            myChart.Set('chart.hmargin', 10);
            myChart.Set('chart.linewidth', 2);
            myChart.Set('chart.tickmarks', 'endcircle');
            myChart.Set('chart.labels', ['Hoolio','Richard','Jack','Kenny','Ivan','Pete','Rodrigo','Luis','Fred','John']);
            myChart.Draw();
        }
    }
</script>

Timed AJAX calls

If you wanted a continually updating chart similar to the one shown here, you could put in a setTimeout() call that calls the window.onload function every 2 seconds. Eg:

window.onload = function (e)
{
    AjaxCall('http://' + location.host + '/getdata.html', myCallback);

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

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