I am trying to acreate dynamic charts using Google charts and PHP MySql.
Here is what I am doing.
My PHP to get average of columns:
<?php
$response = array();
require_once dirname(__FILE__) . '/../includes/DbOperation.php';
// opening db connection
$db = new DbOperation();
if($db->averageAll()){
$response['error']=false;
$response['message']='Team added successfully';
}else{
$response['error']=true;
$response['message']='Could not add team';
}
?>
In the DbOperations code i have a function called averageAll():
// My PHP Function
public function averageAll(){
$query = "SELECT AVG(concept1) AS c1, AVG(concept2) AS c2, AVG(concept3) AS c3, AVG(concept4) AS c4, AVG(concept5) AS c5, AVG(concept6) AS c6 FROM KeyPad";
if ($stmt = $this->conn->prepare($query)) {
$alldata = array();
$stmt->execute();
$stmt->bind_result($c1, $c2, $c3, $c4, $c5, $c6);
while ($stmt->fetch()) {
$tempArr = array();
array_push($tempArr, array("label" => "Concept", "type" =>"String"));
array_push($tempArr, array("label" => "Time", "type" =>"number"));
array_push($alldata, $tempArr);
array_push($alldata, array("C1", $c1));
}
echo json_encode($alldata, JSON_NUMERIC_CHECK);
$stmt->close();
}
$this->conn->close();
}
When I run this code, I get the results in following json format:
[
[
{label: "Concept",type: "String"},
{label: "Time", type: "number"}
],
["C1", 2.8890909090909],
["C2", 1.28376],
]
Now my charts HTML looks like this:
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
//alert(result);
var jsonData = $.ajax({
url: "http://www.ssdesigninteractive.com/keypad/api/readaverage.php",
dataType: "json",
async: false
}).responseText;
var data = google.visualization.DataTable(jsonData);
var options = {
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
</body>
</html>
When I run the html, I get the following error in Chrome console:
Uncaught (in promise) Error: Not an array
at gvjs_Fba (jsapi_compiled_default_module.js:84)
at new gvjs_8m (jsapi_compiled_default_module.js:86)
at drawChart (gChart.html:19)
at <anonymous>
My line:19 is this code:
var data = google.visualization.DataTable(jsonData);
I tried both approaches, "DataTable" as well as "arrayToDataTable" Both don't work.
Can someone help me find out what I might be doing wrong? Thanks.
It looks like you're using the wrong syntax for retrieving the responseText
. See how do I get the reponse text from ajax / jquery?