Real-time Google chart update with comet

I want to use the Google Chart to create a bar chart that is updated in real time. 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 on the client and update the schedule.

Here is an example chart on 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 think I could use Ajax-Request to pull data every few seconds and redraw the chart. But maybe there are some inbuild-Methods in Google Charts that I miss. I also read a lot about Comet , but I never realized this concept.

Anyone else run into this problem?

+5
1

AJAX - :

// 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();
}

Comet , - Socket.Io javascript .

Comet , AJAX . , AJAX .

+2

All Articles