简体   繁体   中英

Using Google Charts with PHP Data

I'm trying to produce a pie graph using Google Charts, the data I want to use is in a MySQL database, so I've created a script to fetch that data and parse it into JSON which ideally will then populate the graph.

I've created the script and checked that it receives the data and that it is in JSON which it is but all I get is 'Table has no columns', can anyone see where I've gone wrong?

Page To Display Graph

      <!--Load the AJAX API-->
      <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
      <script type="text/javascript">

        // Load the Visualization API and the corechart package.
        google.charts.load('current', {'packages':['corechart']});

        // Set a callback to run when the Google Visualization API is loaded.
        google.charts.setOnLoadCallback(drawChart);

        // Callback that creates and populates a data table,
        // instantiates the pie chart, passes in the data and
        // draws it.
        function drawChart() {
          var jsonData = $.ajax({
              url: "scripts/charts/popularColours.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('chart_div'));
          chart.draw(data, {width: 400, height: 240});
        }
      </script>

Later on down the same page I have:

<div id="chart_colours"></div>

My popularColours.php page

$dsn = "";
$options = [
  PDO::ATTR_EMULATE_PREPARES   => false, // turn off emulation mode for "real" prepared statements
  PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, //make the default fetch be an associative array
];
try {
  $pdo = new PDO($dsn, "dbu300121", "3DD63tJXYpP%", $options);
} catch (Exception $e) {
  error_log($e->getMessage());
  exit('There has been an unexpected error, please try again last if the issue continues then contact your IT Support team.'); //something a user can understand
}

$statement = $pdo->prepare("SELECT veh_colour, COUNT(*) as col FROM cst_vehicle GROUP BY veh_colour ORDER BY 2 DESC LIMIT 6");
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo $json;

Just so you can see, this is the data returned

[{"veh_colour":null,"col":206},{"veh_colour":"Black Pearl","col":9},{"veh_colour":"dynamic red","col":8},{"veh_colour":"Battersea Blue","col":6},{"veh_colour":"Arctic White","col":6},{"veh_colour":"Laser Blue","col":5}]

Did you try to encode the response properly? Right now the response is sent as a default text response, but you can let PHP tell your browser/ client that the response is actually JSON:

Adding this right before you echo should do that:

header("Content-Type: application/json");

However, jQuery might have guessed that. Maybe the issue is on the JS side of things. Have you tried something like this, instead of calling.responseText directly?

 $.ajax({ // your parameters }).done(function( data ) { // data should be the JSON response });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM