Create Realtime Chart Without Page Refresh using FusionCharts Free and Ajax (prototype.js)

Bookmark on del.icio.us

fusioncharts-150x150We receive a request from our reader to create simple realtime chart update but without page refresh. Fortunately there are many solutions to do this, but now we will cover using a nice flash charting component called FusionCharts. FusionCharts comes with several edition, but now we will use the FusionCharts Free version. You can download it from http://www.fusioncharts.com/free/. By the time of this writing, FusionCharts Free version is 2.2.

Scenario
Now we will talk about the scenario. We will create realtime chart data update that reflect to price fluctuation. There is a line type chart to visualize the price fluctuation. The data of price fluctuation will be fetched from database every 5 seconds using Ajax call and then display the latest 5 (five) data to the chart without any page refresh.

Important Notes
We assume you already familiar with deploying the FusionCharts Free and have experience using prototype.js, since we don’t explain every details of the tools we used in this article. Please refer to FusionCharts Free documentation about deploying the chart and prototype.js documentation about the usage of the library.

Let’s do it
1. You have to download the FusionCharts Free version, extract it, and copy the chart FCF_Line.swf (from the Chart folder) to your web root folder.

2. Copy FusionCharts.js (from JSClass folder) to your web root folder.

3. Download prototype.js from www.prototypejs.org and save it as prototype.js on your web root folder. We will use prototype.js to do the Ajax call.

4. Now prepare the table to store the fictional price fluctuation. Here is the simple table structure. We only need 2 (two) fields.

- update_datetime = store the date time
- price = store the price

1
2
3
4
CREATE TABLE IF NOT EXISTS `price_fluctuation` (
  `update_datetime` datetime NOT NULL,
  `price` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

5. Populate the table with some data. You can insert some data like below.

1
2
3
4
5
6
INSERT INTO price_fluctuation ('update_datetime', 'price') VALUES
('2010-02-18 14:53:48', 2500),
('2010-02-18 14:54:06', 3000),
('2010-02-18 14:54:30', 2700),
('2010-02-18 14:54:49', 2550),
('2010-02-18 14:55:01', 2650);

6. Now we will create the page that display the chart. Here is the page.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<html>
<head>
	<script type="text/javascript" src="FusionCharts.js"></script>
	<script type="text/javascript" src="prototype.js"></script>
</head>

<body bgcolor="#ffffff">
<center>Demo of Dynamic Price Fluctuation on FusionCharts Free<br/>
Copyright &copy; Sony AK Knowledge Center - www.sony-ak.com</center>
	<div id="chartdiv" align="center"></div>
	<script type="text/javascript">
			var myChart = new FusionCharts("FCF_Line.swf", "myChartId", "600", "400", "0", "1");
	    myChart.setDataURL('get_latest_data.php');
	    myChart.render("chartdiv");
	</script>
</body>
</html>
<script type="text/javascript">
	new PeriodicalExecuter(function getLatestData() {
		new Ajax.Request('get_latest_data.php', {
			  method: 'get',
			  onSuccess: function(transport) {
			    updateChartXML('myChartId', transport.responseText);
			  }
			});
	}, 5);
</script>

Save it as index.php.

7. See on above code, we use PeriodicalExecuter class to do Ajax call to script ‘get_latest_data.php’ on server. The ‘get_latest_data.php’ will provide you with latest 5 (five) price fluctuation from the database. After we receive the data through the callback function, then we pass the data to chart using updateChartXML() function on FusionCharts.js.

Important Notes (Updated on March 3, 2010)
Our reader report to me that he cannot use updateChartXML() function on his FusionCharts v3. Please note that updateChartXML() function is only available on FusionCharts.js on FusionCharts Free edition. If you use FusionCharts v3 you must use setDataXML() function. Here is the example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<script type="text/javascript">
	new PeriodicalExecuter(function getLatestData() {
		new Ajax.Request('latest_earthquake_data.php?anim=0', {
			  method: 'get',
			  onSuccess: function(transport) {
			    // updateChartXML only applies for FusionCharts Free
			    //updateChartXML('earthQuakeId', transport.responseText);

                            // below is for FusionCharts v3 users
                            var chartObj = getChartFromId("earthQuakeId");
	  		    chartObj.setDataXML(transport.responseText);
			  }
			});
	}, 20);
</script>

Here is the code for the ‘get_latest_data.php’ script.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?php
  // script name: get_latest_data.php
  // coder: Sony AK Knowledge Center - www.sony-ak.com
  // code updated on Feb 26, 2010

  $dbConn = mysql_connect('your_db_host', 'your_db_username', 'your_db_password') or die("Connection to database failed, perhaps the service is down !!");
  mysql_select_db('your_db_name') or die("Database name not available !!");

  $resultSet = mysql_query("SELECT *, date_format(update_datetime, '%H:%i') AS time_only FROM price_fluctuation ORDER BY update_datetime DESC LIMIT 5", $dbConn);
  $rowCount = mysql_num_rows($resultSet);

  $xmlData = "<graph caption='Price Fluctuation (in USD)' yAxisMinValue='1000' yAxisMaxValue='5000' animation='0' canvasBorderColor='FFFFFF' xAxisName='Time' yAxisName='Price' showNames='1' decimalPrecision='0' formatNumberScale='0'>";

  $index = $rowCount - 1;
  for ($i=0;$i<$rowCount;$i++) {
  	$updateDatetime = mysql_result($resultSet, $index, "time_only");
  	$price = mysql_result($resultSet, $index, "price");
  	$xmlData .= "<set name='" . $updateDatetime . "' value='" . $price . "' color='000000' />";
  	$index--;
  }

  $xmlData .= "</graph>";

  // insert new data, to make fluctuation effect on the chart
  mysql_query("INSERT INTO price_fluctuation (update_datetime, price) VALUES (now(), " . rand(1000, 5000) . ")", $dbConn);

  echo $xmlData;
?>

You can adjust the database connection above with your environment.

8. Done, our dynamic data chart prototype already finished. You can try to run the index.php from your web server and if everything is OK, your chart will be displayed with random data that represents the price fluctuation. Below is the screen capture of the result.

price_fluctuation_with_fusioncharts_freeDynamic chart data update using FusionCharts Free

The logic is simple, when we call index.php on the first time, the FusionChart will call ‘get_latest_data.php’ through setDataURL() function, then on the bottom of the script will call PeriodicalExecuter from prototype.js to do Ajax call. The PeriodicalExecuter will call ‘get_latest_data.php’ every 5 seconds and send the returned data to the chart without page refresh. This article is just an idea and still can be improved further.

  1. No comments yet.

  1. No trackbacks yet.