0
votes

This is my array.php where json data come from the database and i am getting a perfect out from below script

$table = [];
  $table['cols'] = array(
      array('id' => '', 'label' => 'Topping', 'type' => 'string'),
      array('id' => '', 'label' => 'Slices', 'type' => 'number')
      );    

$tableName = array('1' => "tb", '2' => 'tb1');
foreach ($tableName as $key => $value) {

    $row = [];
    $qry = "SELECT topping, slices FROM $value";
    $result = mysqli_query($con,$qry);
     foreach ($result as $row) {
        $temp = [];
          $temp[] = array('v' => (string) $row['topping']);
      $temp[] = array('v' => (int) $row['slices']); 
      $rows[] = array('c' => $temp);        
     }
     $result->free();
             $table['rows'] = $rows;
}
mysqli_close($con);
$jsonTable = json_encode($table, true);
echo $jsonTable;

**Array.php Data Output Ex: **

{"cols":[{"id":"","label":"Topping","type":"string"},{"id":"","label":"Slices","type":"number"}],"rows":[{"c":[{"v":"MAX"},{"v":150}]},{"c":[{"v":"MAX1"},{"v":59}]},{"c":[{"v":"MAX2"},{"v":15}]},{"c":[{"v":"MAX3"},{"v":153}]},{"c":[{"v":"MAX4"},{"v":8}]},{"c":[{"v":"MAX5"},{"v":25}]},{"c":[{"v":"MAX6"},{"v":65}]}]

}


This is my Ajax Function where i caling data from array.php

var jsonData = $.ajax({
url: "array.php",
dataType:"json",
}).responseText;

var data = new google.visualization.DataTable(JSON.parse(jsonData)); var options = { title: 'My Daily Activities' }; var chart = new google.visualization.PieChart(document.getElementById('piechart')); chart.draw(data, options);

**But I still getting errors on this please help **

1
Pls any one can help me on this ?Rimaz

1 Answers

3
votes

OK, I've copied your json output into a php file (jsondata.php) like this:

$out = '{"cols":[{"id":"","label":"Topping","type":"string"},{"id":"","label":"Slices","type":"number"}],"rows":[{"c":[{"v":"MAX"},{"v":150}]},{"c":[{"v":"MAX1"},{"v":59}]},{"c":[{"v":"MAX2"},{"v":15}]},{"c":[{"v":"MAX3"},{"v":153}]},{"c":[{"v":"MAX4"},{"v":8}]},{"c":[{"v":"MAX5"},{"v":25}]},{"c":[{"v":"MAX6"},{"v":65}]}]}';
echo $out; 

Using that, I've modified a little bit your javascript

  var jsonData = $.ajax({
      url: "jsondata.php",
      dataType: "json",
      async: false
      }).responseText;

  // Create our data table out of JSON data loaded from server.
  var data = new google.visualization.DataTable(jsonData);

  // Instantiate and draw our chart, passing in some options.
  var chart = new google.visualization.PieChart(document.getElementById('piechart'));
  var options = { title: 'My Daily Activities' };
  chart.draw(data, options);

Notice 2 things:

  • The async:false inside the Ajax call. This actually goes against the very essence of Ajax but it is how google shows the examples and it was also the easiest way to solve your problem.

  • The var data = new google.visualization.DataTable(jsonData);

This worked for me, hope it solves your problem.