Although I have no prior experience with Google Charts, I am currently attempting to graph temperature data collected from sensors placed around my house. Unfortunately, I keep encountering an Exception error. I suspect the issue lies in the JSON format not being correct, but I'm struggling to determine the necessary format and how to modify my script to generate JSON accordingly.
The PHP script provided below is responsible for generating JSON data from the database:
<?php
require_once ("config.php");
$array = array();
$res = mysqli_query($con, "SELECT * FROM sensors WHERE vera_variable='CurrentTemperature'");
while ($row = mysqli_fetch_array($res)) {
$sensor_id = $row['sensor_id'];
$sensor_name = $row['sensor_name'];
$res2 = mysqli_query($con, "SELECT * FROM logs WHERE sensor_id='$sensor_id'");
while ($row2 = mysqli_fetch_array($res2)) {
$time = strtotime($row2['log_time']);
$formattedTime = date("m-d-y g:i", $time);
$sensor_value = $row2['sensor_value'];
$array[$formattedTime][$sensor_name] = $sensor_value;
}
}
$json = json_encode($array, JSON_PRETTY_PRINT);
echo "<pre>" . $json . "</pre>";
?>
An example output of the script includes a date, multiple sensors, and their corresponding values.
{
"12-12-15 8:35": {
"Living Room Temperature": "18.3",
"Outside Temperature": "-5",
"Mud Room Temperature": "16.0",
"Basement Temperature": "14.0"
},
// additional data entries...
}
Beyond this point is a simple example chart using JSON:
<html>
<head>
<script language="javascript" type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<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 jsonData = $.ajax({
url : "json_temp.php",
dataType : "json",
async : false
}).responseText;
var obj = window.JSON.stringify(jsonData);
var data = google.visualization.arrayToDataTable(obj);
var options = {
title : 'Graph'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
Upon trying to load the graph, Chrome displays the following error message:
Uncaught Error: Not an arraylha @ format+en,default+en,ui+en,corechart+en.I.js:191bha @ format+en,default+en,ui+en,corechart+en.I.js:193drawChart @ temperature.php:22