I want to use Google Chart to create a bar chart that gets updated in realtime. When the user loads the page, I want to show the current results. But as soon as the data in my database changes, I would like to push these changes to the client and update the graph.
Here is a bar chart example from the Google Charts page:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Year');
data.addColumn('number', 'Sales');
data.addColumn('number', 'Expenses');
data.addRows([
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var options = {
title: 'Company Performance',
vAxis: {title: 'Year', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
I guess I could use an Ajax-Request to pull the data every some seconds and redraw the chart. But maybe there is some inbuild-Method in Google Charts that I am missing. I also read a lot about Comet, but I never implemented that concept.
Has anyone else run into that issue?
Implementing AJAX on a timer is the easiest solution:
// using jQuery for simplicity, but you can implement in other libraries or vanilla javascript if you want
function drawChart() {
var options = {
title: 'Company Performance',
vAxis: {title: 'Year', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
function updateChart () {
$.ajax({
url: 'path/to/data/source/',
data: {/* any parameters you need to pass to the server to get your data back */},
dataType: /* text, json, XML, whatever your server returns */,
success: function (response) {
// use response to create/update DataTable
chart.draw(data, options);
// update the chart again in 2 seconds
setTimeout(updateChart, 2000);
},
error: function (response) {
// handle errors
}
});
}
updateChart();
}
Using a Comet service is a bit more complicated to implement, as it requires setting up something like Socket.Io in javascript and on your server.
Using a Comet service will guarantee the freshest data in the chart at all times, while AJAX is simpler to implement. Comet requires sustaining an active connection to your server while AJAX makes multiple independent requests.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With