Real-time graphing

From JSXGraph Wiki
Revision as of 08:07, 15 May 2010 by A WASSERMANN (talk | contribs)

This little script shows how to graph the data from a sensor in a web browser. Using AJAX, the web browser retrieves once per second data from the web server by calling the script fakesensor.php.

Here, fakesensor.php just returns a random number, but one can image that real sensor data can be accessed similarly.

The underlying JavaScript code

  <script type="text/javascript" src=""></script>
    #jxgbox {
var brd, g, 
    xdata = [], ydata = [],

brd = JXG.JSXGraph.initBoard('jxgbox', {axis:true, boundingbox:[0,20,30,-2]});

turt = brd.createElement('turtle',[],{strokecolor:'#999999'});
for (i=5;i<=15;i+=5) {

fetchData = function() {
    new Ajax.Request('/ajax/fakesensor.php', {
        onComplete: function(transport) {
            var t, a;
            if (200 == transport.status) {
                t = transport.responseText;
                a = parseFloat(t);
                if (xdata.length<30) {          
                    xdata.push(xdata.length); // add data to the x-coordinates, if the right border has not been reached, yet
                } else {
                    ydata.splice(0,1);        // remove the oldest entry of the y-coordinates, to make the graph move.
                if (!g) {                   // If the curve does not exist yet, create it.
                    g = brd.createElement('curve', [xdata,ydata],{strokeWidth:3, strokeColor:'yellow'}); 
setInterval(fetchData,1000);  // Start the periodical update

The PHP code of fakesensor.php

   echo mt_rand(0,20);