How do I add data dynamically into a google chart

5.7k Views Asked by At

I have data in my database. Let's say that I have all these for now:

  ['Task', 'Hours per Day'],
  ['Work', 8],
  ['Eat', 2],
  ['Commute', 2],
  ['Watch TV', 2],
  ['Sleep', 7]

DataBase table:

MyDailyRoutineTable
Task       Hours per Day
Work       8
Eat        2
Commute    2
Watch TV   2
Sleep      7
//Do Chores  2 //eventually added
//Exercise   1 //eventually added

I want to be able to add more data from my database if later I decide to put something like 'Do chores' and 'Exercise' I want to read all the values directly from the database which would later be (dynamically filled from data in MyDailyRoutineTable):

  ['Task', 'Hours per Day'],
  ['Work', 8],
  ['Eat', 2],
  ['Commute', 2],
  ['Watch TV', 2],
  ['Sleep', 7],
  ['Do Chores', 2],
  ['Exercise', 1]

instead of:

var data = google.visualization.arrayToDataTable([

      ['Task', 'Hours per Day'],
      ['Work', 8],
      ['Eat', 2],
      ['Commute', 2],
      ['Watch TV', 2],
      ['Sleep', 7]
    ]);

it should be something like:

var data = google.visualization.arrayToDataTable([

      {database data}

    ]);

The last 2 are not accounted for in the jsfiddle. What I want to know is how to read those from a mysql database and add them to the chart.

      google.charts.load('current', {
        'packages': ['corechart']
      });
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {

        var data = google.visualization.arrayToDataTable([
          ['Task', 'Hours per Day'],
          ['Work', 8],
          ['Eat', 2],
          ['Commute', 2],
          ['Watch TV', 2],
          ['Sleep', 7]
        ]);

        var options = {
          title: 'My Daily Activities'
        };

        var chart = new google.visualization.PieChart(document.getElementById('piechart'));

        chart.draw(data, options);
      }
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="piechart" style="width: 900px; height: 500px;"></div>

1

There are 1 best solutions below

0
On

Basically to achieve what you want, you will need to configure php scripts in your backend that will output data in JSON format. You can either send non-google-charts-compliant JSON, and then parse it in your front-end and build your charts, OR you can use google.visualization.arrayToDataTable() method on a google-chart compliant JSON. See link below. Having played around with google charts for quite some time, I would seriously recommend sending google-compliant JSON. Even if it's tedious and can take quite some time, you offload a lot of the calculations server-side and you gain abstraction.

Google Chart JSON format

Building array and formatting JSON for Google Charting API