I am going to output JSON data to a chart using Chart.js, querying a MySQL database for data.
Basically, I made a request (data.php):
<?php
header('Content-Type: application/json');
$con =
if (mysqli_connect_errno($con))
{
echo "Failed to connect to DataBase: " . mysqli_connect_error();
}
else
{
$data_points = array();
$result = mysqli_query($con, "SELECT * FROM condicao order by id desc limit 10");
while($row = mysqli_fetch_array($result))
{
$point = array($row['timestamp'], $row['temperatura']);
array_push($data_points, $point);
}
echo json_encode($data_points, JSON_NUMERIC_CHECK);
}
mysqli_close($con);
?>
Which gave me the following array ( timestamp, temperature):
[
["2014-08-04 23:06:01",16.9],
["2014-08-04 23:03:02",17.1],
["2014-08-04 23:00:02",17.1],
["2014-08-04 22:57:01",17.1],
["2014-08-04 22:54:01",17.1],
["2014-08-04 22:51:02",17.1],
["2014-08-04 22:48:01",17.2],
["2014-08-04 22:45:02",17.2],
["2014-08-04 22:42:01",17.2],
["2014-08-04 22:39:02",17.2]
]
Now I'm trying to display this on a diagram, but I don’t know how to transfer the first object as a label (time stamp), and the second object as data points (temperature).
Here is the code in which I am trying to plot the diagram:
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("data.php", function (result) {
var tempData = {
labels : result,
datasets : [{
fillColor : "rgba(172,194,132,0.4)",
strokeColor : "#ACC26D",
pointColor : "#fff",
pointStrokeColor : "#9DB86D",
data : result
}]
}
var temp = document.getElementById('compradores').getContext('2d');
new Chart(temp).Line(tempData);
});
});
</script>
How can I define the result as the first object for the label (timestamp) and the second object in the array as data points (temperature)?
In the way I do above, I get both a timestamp and temperature as shortcuts.
result[0], result['timestamp'] .., .
!