Updating Ajax Charts

by Naneau

HTML is a markup language for producing static pages. When trying to present data to your end users that changes over time, that can be a problem. There are different ways to get around that. The whole Ajax hype floats on it.

Charts are a way of presenting information. Because they are images you need some kind of charting engine to create them. There are plenty of those around for PHP. A new trend has been charting engines written in JavaScript. I like the concept, because it allows for graphs that update in the browser.

I have written a little JavaScript that builds on PlotKit. It gets data from a server every x seconds and updates a graph accordingly. It could be useful for displaying stock quotes, or some other data that changes over time. See it in action in the demo.

Providing it with data is a breeze.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public function graphdata2Action() {
    $ts = round(time() / 5);
    //yes, this IS interesting
   
    for ($x = 0; $x < 10; $x++) {
        $return[] = array($x, (($ts + $x) % 5) + 1);
    }
    //10 points with a modulo the time

    Zend_Loader::loadClass('Zend_Json');
    $json = Zend_Json::encode($return);
    //result encoded in JSON

    $this->getResponse()->setHeader('Content-Type', 'text/javascript');
    $this->getResponse()->setBody($json);
    //encode result and pass it back
}