Loading
Feeding & Retrieving Data Through API
The FusionCharts Suite XT real-time charts let you feed and retrieve data using the JavaScript API, instead of using the data provider page.
In this section, you will be shown how you can:
Feeding Data using JavaScript
When feeding data using the JavaScript API, you need to ensure that the format of the data feed is same as that specified by the real-time data provider page.
You can use the feedData(strData)
method to feed data to the chart. Here, strData
is a string value which contains data in exactly the same format as that provided by the real-time data provider page.
A real-time line chart for which data is set using the feedData(strData)
method is shown below:
{
"chart": {
"caption": "Harry's Supermart",
"subCaption": "Real-time Stock Price monitor",
"showrealtimevalue": "1",
"paletteColors": "#008ee4",
"refreshinterval": "2",
"borderAlpha": "0",
"yaxismaxvalue": "100",
"numdisplaysets": "10",
"showLegend": "0",
"canvasBorderAlpha": "20",
"labeldisplay": "rotate",
"bgAlpha": "0",
"showValues": "0",
"numberPrefix": "$",
"showlabels": "1",
"animation": "0",
"showRealTimeValue": "0"
},
"categories": [
{
"category": [
{
"label": "Start"
}
]
}
],
"dataset": [
{
"seriesname": "Harry's SuperMart",
"alpha": "100",
"data": [
{
"value": "20"
}
]
}
]
}
<html>
<head>
<title>My first chart using FusionCharts Suite XT</title>
<script type="text/javascript" src="http://static.fusioncharts.com/code/latest/fusioncharts.js"></script>
<script type="text/javascript" src="http://static.fusioncharts.com/code/latest/themes/fusioncharts.theme.fint.js?cacheBust=56"></script>
<script type="text/javascript">
FusionCharts.ready(function(){
var fusioncharts = new FusionCharts({
id: "mychart-1",
type: 'realtimeline',
renderAt: 'chart-container',
width: '600',
height: '300',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Harry's Supermart",
"subCaption": "Real-time Stock Price monitor",
"showrealtimevalue": "1",
"paletteColors": "#008ee4",
"refreshinterval": "2",
"borderAlpha": "0",
"yaxismaxvalue": "100",
"numdisplaysets": "10",
"showLegend": "0",
"canvasBorderAlpha": "20",
"labeldisplay": "rotate",
"bgAlpha": "0",
"showValues": "0",
"numberPrefix": "$",
"showlabels": "1",
"animation": "0",
"showRealTimeValue": "0"
},
"categories": [{
"category": [{
"label": "Start"
}]
}],
"dataset": [{
"seriesname": "Harry's SuperMart",
"alpha": "100",
"data": [{
"value": "20"
}]
}]
},
events: {
'rendered': function(evt, args) {
//Format minutes, seconds by adding 0 prefix accordingly
function formatTime(time) {
(time < 10) ? (time = "0" + time) : (time = time);
return time;
}
evt.sender.chartInterval = setInterval(function() {
//Get reference to the chart using its ID
var chartRef = evt.sender,
//We need to create a querystring format incremental update, containing
//label in hh:mm:ss format
//and a value (random).
currDate = new Date(),
label = formatTime(currDate.getHours()) + ":" + formatTime(currDate.getMinutes()) + ":" + formatTime(currDate.getSeconds()),
//Get random number between 30 & 35 - rounded to 2 decimal places
randomValue = Math.floor(Math.random() * 500) / 100 + 30,
//Build Data String in format &label=...&value=...
strData = "&label=" + label + "&value=" + randomValue;
//Feed it to chart.
chartRef.feedData(strData);
}, 5000);
},
"disposed": function(evt, args) {
clearInterval(evt.sender.chartInterval);
}
}
}
);
fusioncharts.render();
});
</script>
</head>
<body>
<div id="chart-container">FusionCharts XT will load here!</div>
</body>
</html>
In the above data, we:
-
Instantiate the chart without any data and with one dataset.
-
Define a custom function
updateData()
that is invoked with a JavaScript interval - this function builds the data (in the real-time data format) to be specified for the chart. In this code, the function contains a random value for demonstration purposes. -
Feed data to the chart using the
feedData(strData)
method.
Retrieving Data using JavaScript
Real-time charts allow you to get the current view of data (i.e., the data which is currently being shown on the chart) using JavaScript.
Additionally, the charts allow you to track events in JavaScript whenever new data is provided to the chart (either from the real-time data provider page or using JavaScript).
You can get data using:
-
the
FC_ChartUpdated()
method -
the
realTimeUpdateComplete
andrealTimeUpdateError
events -
the
getData()
method
The FC_ChartUpdated() Method
Real-time charts let you track data updates for the real-time chart(s) rendered on a page. You can configure charts to notify you of new data fetches and data updates by calling the FC_ChartUpdated(DOMId)
JavaScript method.
You can define the FC_ChartUpdated()
method in your HTML code as shown below:
function FC_ChartUpdated(DOMId) {
//Check if DOMId is that of the chart we want
if (DOMId == "ChId1") {
//Get reference to the chart
var chartRef = FusionCharts(DOMId);
//Now you can do anything with the chart...
}
}
Whenever a real-time chart (present in this page) receives new data (from the data provider page or the JavaScript feedData()
method), it will now call the FC_ChartUpdated()
method and pass its DOM Id to this method.
If you have multiple real-time charts on the same page, you can use the DOMI d to track which chart was updated and based on that, take future actions.
The realTimeUpdateComplete and realTimeUpdateError Events
The realTimeUpdateComplete
event is raised every time a real-time chart or gauge completes updating itself with new data.
A sample implementation of the realTimeUpdateComplete
event is shown below:
FusionCharts("mychart").addEventListener("RealtimeUpdateComplete",
function(event, parameter)
{
showData();
}
);
Existing JavaScript implementations using the FC_ChartUpdated event will continue to function without any problem.
The realtimeUpdateError
event is raised when an error occurs while updating data for a real-time chart or gauge. This event passes the HTTP Status (as number) of the error occurred.
A sample implementation of the realtimeUpdateError
event is shown below:
FusionCharts("mychart").addEventListener("RealtimeUpdateError",
function(event, parameter)
{
document.getElementById('ErrorView').innerHTML = "Problem occurred while updating real-time data. The error status code is" + parameter.httpStatus;
}
);
The getData() Method
For any real-time chart present in the HTML page, you can use the getData()
method to get the current chart data in a JavaScript array.
A real-time column chart configured to retrieve data using the getData()
method is shown below:
{
"chart": {
"caption": "Harry's Supermart - Bakersfield Central",
"subCaption": "Footfalls",
"showrealtimevalue": "1",
"paletteColors": "#008ee4,#9b59b6",
"borderAlpha": "0",
"yaxismaxvalue": "20",
"numdisplaysets": "10",
"usePlotGradientColor": "0",
"plotBorderAlpha": "0",
"canvasBorderAlpha": "20",
"labeldisplay": "rotate",
"slantLabels": "1",
"showLegend": "0",
"bgAlpha": "0",
"showValues": "0",
"numbersuffix": " Customers",
"showlabels": "1",
"animation": "0",
"showRealTimeValue": "0"
},
"categories": [
{
"category": [
{
"label": "Start"
}
]
}
],
"dataset": [
{
"seriesname": "Footfall",
"alpha": "100",
"data": [
{
"value": "5"
}
]
}
]
}
<html>
<head>
<title>My first chart using FusionCharts Suite XT</title>
<script type="text/javascript" src="http://static.fusioncharts.com/code/latest/fusioncharts.js"></script>
<script type="text/javascript" src="http://static.fusioncharts.com/code/latest/themes/fusioncharts.theme.fint.js?cacheBust=56"></script>
<script type="text/javascript">
FusionCharts.ready(function(){
var fusioncharts = new FusionCharts({
id: "mychart-2",
type: 'realtimecolumn',
renderAt: 'chart-container',
width: '600',
height: '210',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Harry's Supermart - Bakersfield Central",
"subCaption": "Footfalls",
"showrealtimevalue": "1",
"paletteColors": "#008ee4,#9b59b6",
"borderAlpha": "0",
"yaxismaxvalue": "20",
"numdisplaysets": "10",
"usePlotGradientColor": "0",
"plotBorderAlpha": "0",
"canvasBorderAlpha": "20",
"labeldisplay": "rotate",
"slantLabels": "1",
"showLegend": "0",
"bgAlpha": "0",
"showValues": "0",
"numbersuffix": " Customers",
"showlabels": "1",
"animation": "0",
"showRealTimeValue": "0"
},
"categories": [{
"category": [{
"label": "Start"
}]
}],
"dataset": [{
"seriesname": "Footfall",
"alpha": "100",
"data": [{
"value": "5"
}]
}]
},
"events": {
"beforeRender": function(evtObj, argObj) {
var controllers = document.createElement('div');
// Create div
controllers.innerHTML = '<div><input type="button" style="margin-left:5px;margin-top:5px" value="Get Data" id="getdata_btn" style="margin-left:5px;margin-top:5px" /></div><div id="tableView" style="width:275px;height:75px;overflow-y:auto; display:none;border: none;margin: 3px"></div>';
//Display container div and write table
argObj.container.parentNode.insertBefore(controllers, argObj.container.nextSibling);
},
"rendered": function(evtObj, argObj) {
//Format minutes, seconds by adding 0 prefix accordingly
function formatTime(time) {
return (time < 10) ? (time = "0" + time) : (time = time);
}
function showData() {
//Retrieving the data
var dataArr = evtObj.sender.getData(),
str = "",
valueStyle = "padding: 3px",
fontStyle = "font-weight: bold;font-size: 14px";
//Creating the table format
str += '<table border="1" cellpadding="1" cellspacing="0" bordercolor="#cccccc" width="100%">';
str += ' <tr>';
str += ' <td width="50%" style="' + fontStyle + valueStyle + '">Time</td>';
str += ' <td width="50%" style="' + fontStyle + valueStyle + '">Customers</td>';
str += ' </tr>';
//Preparing html string to create the table with data
for (i = 0; i < dataArr.length; i++) {
if (dataArr[i][0] !== null) {
str += ' <tr>';
str += ' <td width="50%" style="' + valueStyle + '">' + dataArr[i][0] + '</td>';
str += ' <td width="50%" style="' + valueStyle + '">' + dataArr[i][1] + '</td>';
str += ' </tr>';
}
}
str += '</table>';
//Showing the table
document.getElementById("tableView").setAttribute('style', '"display", "block"');
//Adding html string in the div container
document.getElementById("tableView").innerHTML = str;
}
evtObj.sender.chartInterval = setInterval(function() {
//Get reference to the chart using its ID
var chartRef = evtObj.sender;
//We need to create a querystring format incremental update, containing
//label in hh:mm:ss format
//and a value (random).
var currDate = new Date();
var label = formatTime(currDate.getHours()) + ":" + formatTime(currDate.getMinutes()) + ":" + formatTime(currDate.getSeconds());
//Get random number between 5 & 20 - rounded
var footfall = Math.round(Math.random() * 15) + 5;
var strData = "&label=" + label + "&value=" + footfall;
//Feed it to chart.
chartRef.feedData(strData);
}, 5000);
//Getting the data on button click and diplaying the same
document.getElementById("getdata_btn").addEventListener("click", function() {
showData();
});
},
"disposed": function(evt, args) {
clearInterval(evt.sender.chartInterval);
}
}
}
);
fusioncharts.render();
});
</script>
</head>
<body>
<div id="chart-container">FusionCharts XT will load here!</div>
</body>
</html>
The following code snippet shows how you can use the getData()
method for the above chart:
function showData() {
//Retrieving the data
var dataArr = FusionCharts("mychart").getData(),
i,
str = "";
//Creating the table format
str += '<table border="1" cellpadding="1" cellspacing="0" bordercolor="#cccccc" width="100%">';
str += ' <tr>';
str += ' <td width="50%" class="fontBold valueFont">Time</td>';
str += ' <td width="50%" class="fontBold valueFont">Customers</td>';
str += ' </tr>';
//Preparing html string to create the table with data
for (i = 0; i < dataArr.length; i++) {
if (dataArr[i][0] !== null) {
str += ' <tr>';
str += ' <td width="50%" class="valueFont">' + dataArr[i][0] + '</td>';
str += ' <td width="50%" class="valueFont">' + dataArr[i][1] + '</td>';
str += ' </tr>';
}
}
str += '</table>';
//Adding html string in the div container
document.getElementById('tableView').innerHTML = str;
}
Whenever the data for a chart with the myChart
ID updates in the page, the showData()
function is invoked. This function gets the new data for the chart in a JavaScript array using the getData()
method. The showData()
function then creates an HTML table and renders the new data in that table.
The structure of the JavaScript array returned by the getData()
function is shown below:
[0,0] - Empty |
[0,1]- Dataset series name |
[0,2] - Dataset series name |
[0,n] - Dataset series name |
[1,0] - Category label of data index 1 |
Data for dataset [1] data index [1] |
Data for dataset [2] data index [1] |
Data for dataset [n] data index [m] |
,0] - Category label of data index 2 |
Data for dataset [1] data index [2] |
Same as above |
Same as above |
[m,0] - Category label of data index m |
Data for dataset [n] data index [m] |
Same as above |
Same as above |
[m,0] - Category label of data index m |
Same as above |
Same as above |
Same as above |
[m,0] - Category label of data index m |
Same as above |
Same as above |
Same as above |
When you click the Get Data
button rendered below the chart, the HTML table is populated with data updates as shown below:
Time | Customers |
---|---|
14:37:22 |
13 |
14:37:27 |
16 |
14:37:32 |
6 |
14:37:37 |
16 |
14:37:42 |
7 |
14:37:47 |
16 |
14:37:52 |
7 |
14:37:57 |
16 |
14:38:02 |
11 |
14:38:07 |
19 |
Using the methods explained above, you can build a wide variety of interactive AJAX driven applications. You can use the chart as an interface to retrieve the data and then handle it in your JavaScript code.