Making an updating graph using javascript and jpgraph

This is a pretty cool way to update a graph on a webpage without having to refresh the entire page. Javascript is an easy language to get started in, today was my first time using it and within a few hours it was doing what I wanted. This stack overflow question was useful for my needs. I used the code from the first answer and just added in some simple code to refresh the image when the counter reaches 0. I also want to find out how to make the counter wait for the image to load before it continues counting because sometimes there is a lag between the counter hitting zero and the graph updating, so thats the next thing to try out. For now I just want to document what I have got working so far.

The PHP code that produces the graph:

The PHP script used to produce this graph is very similar to my previous post about using jpgraph with MySQL. This time though, the numbers being plotted aren’t coming from a database, they are just random numbers generated using the rand function in PHP.

Using javascript to refresh the image from the same URL

One cool thing about javascript is how easy it is to mess about with and change the properties of HTML tags. One small note about loading an image from the same URl is that some unique identifier should be appended to the end to force the browser to load the image from source as opposed to using the cache. This is achieved in the example below by putting a ‘?’ at the end of the URL and then adding the date and time. This ensures that every time a new image is loaded it will have a unique URL.

and thats it! This will be useful for viewing something like sensor data is close to real time. For example if there was an internet connected temperature sensor with the temperature data being placed in a MySQL database a PHP script to get the last 10 minutes worth of entries and then update the graph would be fairly simple to do.