Google Chart API invalid JSON string on Line Chart - php

I'm trying to use Google Charts API to create a line chart based on a MySQL database. The database contains temperatures and timestamps.
I have getData.php to get the data and turn it into a JSON.
<?php
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$qry = "SELECT * FROM temp";
$result = mysqli_query($conn,$qry);
$table = array();
$table['cols'] = array(
array('label' => 'Time', 'type' => 'datetime'),
array('label' => 'Temperature', 'type' => 'number')
);
$rows = array();
foreach($result as $row){
$temp = array();
//$temp[] = array('v' => 'Date(' . $row['time'] . ')'); OLD
//turn timestamps into correct datetime form Date(Y,n,d,H,i,s)
$temp[] = array('v' => 'Date('.date('Y',strtotime($row['time'])).',' .
(date('n',strtotime($row['time'])) - 1).','.
date('d',strtotime($row['time'])).','.
date('H',strtotime($row['time'])).','.
date('i',strtotime($row['time'])).','.
date('s',strtotime($row['time'])).')');
$temp[] = array('v' => (float) $row['temperature']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table, true);
echo $jsonTable;
?>
The timestamps are transformed to "Date(Year, Month, Day, Hours, Minutes, Seconds, Milliseconds)" format as per Google's instructions here: https://developers.google.com/chart/interactive/docs/datesandtimes#dates-times-and-timezones
Here is my main.html. It's based on the Google's example( https://developers.google.com/chart/interactive/docs/php_example#exampleusingphphtml-file )
<html>
<head>
<!--Load the AJAX API-->
<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">
// Load the Visualization API and the corechart package.
google.charts.load('current', {'packages':['line']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "getData.php",
dataType: "json",
async: false
}).responseText;
var data = new google.visualization.DataTable(jsonData); //Line 27
var options = {'title':'Temperature',
'width':720,
'height':480};
var chart = new google.charts.Line(document.getElementById('chart_div'));
//chart.draw(data, options);
//chart.draw(data, {width: 400, height: 240});
chart.draw(data, google.charts.Line.convertOptions(options));
}
</script>
</head>
<body>
<div id="chart_div"><p id="test"></p></div>
</body>
<html>
The website is blank and Chrome debugger shows this error:
Uncaught Error: Invalid JSON string:
<body>
{"cols":[{"label":"Time","type":"datetime"},{"label":"Temperature","type":"number"}],"rows":[{"c":[{"v":"Date(2016,3,14,10,36,30)"},{"v":22}]},{"c":[{"v":"Date(2016,3,14,10,37,31)"},{"v":25}]},{"c":[{"v":"Date(2016,3,14,10,37,53)"},{"v":21}]},{"c":[{"v":"Date(2016,3,15,01,23,37)"},{"v":21}]}]}
</body>
yl # VM1981:170
Ol # VM1981:174
Sp # VM1981:234
drawChart # main.html:27
google.a.b.Na # loader.js:147
g # loader.js:145
The main.html:27 is the var data = new google.visualization.DataTable(jsonData); line.
Here is the JSON formatted with jsonlint
{
"cols": [{
"label": "Time",
"type": "datetime"
}, {
"label": "Temperature",
"type": "number"
}],
"rows": [{
"c": [{
"v": "Date(2016,3,14,10,36,30)"
}, {
"v": 22
}]
}, {
"c": [{
"v": "Date(2016,3,14,10,37,31)"
}, {
"v": 25
}]
}, {
"c": [{
"v": "Date(2016,3,14,10,37,53)"
}, {
"v": 21
}]
}, {
"c": [{
"v": "Date(2016,3,15,01,23,37)"
}, {
"v": 21
}]
}]
}
I'm completely at loss here. The JSON string should be fine and it's validated by jsonlint.com too. Any help would be greatly appreciated.

Copying your code and returning your pasted json string in getData.php I can't reproduce your error.
Please check your ajax response in main.html:
console.log(jsonData);
If I add additional output in getData.php (for example var_dump something), I can create the invalid JSON string error. The
<body>
tag around your JSON string is suspicious though, because in the error message the malformed JSON string is printed, so the tag seems to be part of your JSON-string. Is your php code in getData.php embedded in body-tags?
In main.html you could try:
jsonData=jsonData.replace("<body>", "").replace("</body>", "");
to check, if this might be the problem.

Related

Unable to display x-axis labels on multi-column mysql array in Highcharts

I have a mysql database containing multiple columns of power values captured over time, with time captured in the first column. I would like to plot the power values and display the time of day on the x-axis of a Highcharts chart. I am currently able to display the multiple Power values on the y-axis but I am unable to get the time of day to display on the chart. Here is the PHP code that partially works:
<?php
// Connect to database
$con = mysqli_connect("localhost","userid","passwd","power_readings");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Set the variable $rows to the columns Energy_Date and Total_watts
$query = mysqli_query($con,"SELECT Energy_Date,Total_watts FROM combined_readings");
$rows = array();
$rows['name'] = 'Total_watts';
while($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = $tmp['Total_watts'];
}
// Set the variable $rows1 to the columns Energy_Date and Power_watts
$query = mysqli_query($con,"SELECT Energy_Date,Power_watts FROM combined_readings");
$rows1 = array();
$rows1['name'] = 'Neurio_watts';
while($tmp = mysqli_fetch_array($query)) {
$rows1['data'][] = $tmp['Power_watts'];
}
// Set the variable $rows2 to the columns Energy_Date and Solar_watts
$query = mysqli_query($con,"SELECT Energy_Date,Solar_watts FROM combined_readings");
$rows2 = array();
$rows2['name'] = 'Solar_watts';
while($tmp = mysqli_fetch_array($query)) {
$rows2['data'][] = $tmp['Solar_watts'];
}
$result = array();
array_push($result,$rows);
array_push($result,$rows1);
array_push($result,$rows2);
print json_encode($result, JSON_NUMERIC_CHECK);
mysqli_close($con);
?>
Can someone tell me how to change the code to pass the values from the time of day column properly?
Here is what the chart currently looks like:
When I made changes to the PHP to add the 'Energy_Date' field to the array passed to Highcharts (shown below) it results in a blank chart.
The array consists of fields that look like this (a time stamp followed by a power reading, separated by period:
"2018-02-21 16:56:00.052","2018-02-21 16:59:00.052","2018-02-21 17:02:00.039","2018-02-21 17:05:00.039","2018-02-21 17:08:00.039"
<?php
// Connect to database
$con = mysqli_connect("localhost","userid","passwd","power_readings");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Set the variable $rows to the columns Energy_Date and Total_watts
$query = mysqli_query($con,"SELECT Energy_Date,Total_watts FROM combined_readings");
$rows = array();
$rows['name'] = 'Total_watts';
while($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = $tmp['Energy_Date'].$tmp['Total_watts'];
}
// Set the variable $rows1 to the columns Energy_Date and Power_watts
$query = mysqli_query($con,"SELECT Energy_Date,Power_watts FROM combined_readings");
$rows1 = array();
$rows1['name'] = 'Neurio_watts';
while($tmp = mysqli_fetch_array($query)) {
$rows1['data'][] = $tmp['Energy_Date'].$tmp['Power_watts'];
}
// Set the variable $rows2 to the columns Energy_Date and Solar_watts
$query = mysqli_query($con,"SELECT Energy_Date,Solar_watts FROM combined_readings");
$rows2 = array();
$rows2['name'] = 'Solar_watts';
while($tmp = mysqli_fetch_array($query)) {
$rows2['data'][] = $tmp['Energy_Date'].$tmp['Solar_watts'];
}
$result = array();
array_push($result,$rows);
array_push($result,$rows1);
array_push($result,$rows2);
print json_encode($result, JSON_NUMERIC_CHECK);
mysqli_close($con);
?>
The html receiving this array looks like this:
<!DOCTYPE html>
<html lang="en">
<title>Combined Values Graph</title>
<head>
<meta http-equiv="refresh" content="180">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var x_values = [];
var chart;
$(document).ready(function() {
Highcharts.setOptions({
colors: ['#4083e9', '#99ccff', '#00ffff', '#e6e6e6', '#DDDF00', '#64E572', '#FF9655', '#FFF263', '#6AF9C4']
});
$.getJSON("values.php", function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'mygraph',
type : 'spline',
borderWidth: 1,
zoomType: 'x',
panning: true,
panKey: 'shift',
plotShadow: false,
marginTop: 100,
height: 500,
plotBackgroundImage: 'gradient.jpg'
},
plotOptions: {
series: {
fillOpacity: 1
}
},
plotOptions: {
series: {
marker: {
enabled: false
}
}
},
title: {
text: 'Combined Power Readings'
},
subtitle: {
text: 'Total = Neurio + Solar Readings in Watts'
},
xAxis : {
title : {
text : 'Time of Day'
}
},
yAxis: {
title: {
text: 'Power (watts)'
},
plotLines: [{
value: 0,
width: 2,
color: '#ff0000',
zIndex:4,
dashStyle: 'ShortDot'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 120,
borderWidth: 1
},
plotOptions : {
spline : {
marker : {
radius : 0,
lineColor : '#666666',
lineWidth : 0
}
}
},
series: json
});
});
});
});
</script>
<script src="https://code.highcharts.com/highcharts.src.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
</head>
<body>
<div class="container" style="margin-top:20px">
<div class="col-md-10">
<div class="panel panel-primary">
<div class="panel-body">
<div id ="mygraph"></div>
</div>
</div>
</div>
</div>
</body>
</html>
I have added the console statement to the bottom of the js like so:
series: json
});
console.log(json);
});
Here's what is shown in the browser console for PHP version 1 (The version that displays the graphs).
Browser console 1
Here's what is shown in the browser console for PHP version 2 (The version that gives a blank chart).
Browser console 2
Thanks for your helpful suggestions. I have changed the while loops to look like this:
while($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = $tmp['Energy_UTC'];
$rows['data'][] = $tmp['Total_watts'];
}
The output of the PHP now looks like this:
[{"name":"Total_watts","data":[1519315164,93,1519315344,354]},{"name":"Neurio_watts","data":[1519315164,76,1519315344,309]},{"name":"Solar_watts","data":[1519315164,17,1519315344,45]}]
The data being passed to Highcharts (from the console) now looks like this:
Browser console 3
The chart is still wrong: the x-axis is not showing the timestamps and the chart is incorrect. Can anyone suggest how to change the PHP or html to correct this?
OK, I have updated the while loops to look like this:
$query = mysqli_query($con,"SELECT Energy_UTC,Total_watts FROM combined_readings");
$rows = array();
$rows['name'] = 'Total_watts';
while($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = [$tmp['Energy_UTC'],$tmp['Total_watts']];
}
The PHP output now looks like this:
[{"name":"Total_watts","data":[[1519387869,423],[1519388049,423],[1519388229,332],[1519388410,514],[1519388590,514]...
and the chart is now displaying UTC timestamps for each power value.
You are writing a large block of code with many duplicated components. I've taken the time to DRY your method. It is best practice to minimize calls to the database, so I've managed to combine your queries into one simple select.
Theoretically, you will only need to modify $colnames_labels to modify your HighChart. I have written inline comments to help you to understand what my snippet does. I have written some basic error checks to help you to debug if anything fails.
Code: (untested)
$colnames_labels=[
'Total_watts'=>'Total_watts',
'Power_watts'=>'Neurio_watts',
'Solar_watts'=>'Solar_watts'
];
$select_clause_ext=''; // declare as empty string to allow concatenation
foreach($colnames_labels as $colname=>$label){
$data[]=['name'=>$label]; // pre-populate final array with name values
// generates: [0=>['name'=>'Total_watts'],1=>['name'=>'Neurio_watts'],2=>['Solar_watts']]
$select_clause_ext.=",$colname";
// generates: ",Total_watts,Power_watts,Solar_watts"
}
$subarray_indexes=array_flip(array_keys($colnames_label)); // this will route resultset data to the correct subarray
// generates: ['Total_watts'=>0,'Power_watts'=>1,'Solar_watts'=>2]
if(!$result=mysqli_query($con,"SELECT UNIX_TIMESTAMP(Energy_Date) AS Stamp{$select_clause_ext} FROM combined_readings ORDER BY Energy_Date")){
$data=[['name'=>'Syntax Error (query error)','data'=>[0,0]]; // overwrite data with error message & maintain expected format
}elseif(!mysqli_num_rows($result)){
$data=[['name'=>'Logic Error (no rows)','data'=>[0,0]];
}else{
while($row=mysqli_fetch_assoc($result)){
foreach($subarray_indexes as $i=>$col){
$data[$i]['data'][]=[$row['Stamp'],$row[$col]]; // store [stamp,watts] data in appropriate subarrays
}
}
}
echo json_encode($data,JSON_NUMERIC_CHECK); // Convert to json (while encoding numeric strings as numbers) and print to screen

JSON PHP Google Visualisation

Trying to get my json output in the right format for a google visualisation line chart but I am clearly doing something wrong as it is returning table has no columns. As explained in the docs I am using Ajax to call a php page.
getData.php
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('water.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
//echo "Opened database successfully\n";
}
$sql =<<<EOF
SELECT * from wT;
EOF;
$data = array();
$data['cols'][] = array('label' => 'Temperature', 'type' => 'number');
$data['cols'][] = array('label' => 'Time', 'type' => 'string');
$rows = array();
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
$temp = array();
$temp[] = array('v' => (float) $row['fishTemp']);
$temp[] = array('v' => (string) $row['time']);
$rows = array('c' => $temp);
$data['rows'][] = $rows;
}
$jsonTable = json_encode($data, true);
var_dump($jsonTable);
$db->close();
?>
base.html
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "getData.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
console.log(jsonData);
//var obj = window.JSON.stringify(jsonData);
var data = new google.visualization.DataTable(jsonData);
var options = {
title: 'Title'
};
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>
The output from the console looks like this....what am I missing?!
"{"cols":[{"label":"Temperature","type":"string"},{"label":"Time","type":"date"}],"rows":[{"c":[{"v":18.25},{"v":"2014-08-19 16:23:23"}]},{"c":[{"v":18.25},{"v":"2014-08-19 16:23:31"}]},{"c":[{"v":18.25},{"v":"2014-08-19 16:23:39"}]},{"c":[{"v":18.25},{"v":"2014-08-19 16:23:47"}]},{"c":[{"v":18.25},{"v":"2014-08-19 16:23:55"}]},{"c":[{"v":18.25},{"v":"2014-08-19 16:24:06"}]},{"c":[{"v":18.25},{"v":"2014-08-19 16:24:14"}]}
Loading dataTable with json accepts dates as a string in the following format: Date(year, month, day[,hour, minute, second[, millisecond]]) where everything after day is optional, and months are zero-based.
So for your first timeStamp, it should be :
{"v":"Date(2014,07,19,16,23,23)"}
If you want to use directly the milliseconds time:
{"v":"Date(1411154603000)}

Highcharts - parse json series

Im using this to draw column highcharts jsfiddle
i use this to gt JSON:
<?php
$query = mysql_query("SELECT
sales_raport_all.from_date,
sales_raport_all.to_date,
sales_raport_all.konto,
SUM(sales_raport_all.saldo_sprzedazy),
SUM(sales_raport_all.wartosc_kosztowa),
SUM(sales_raport_all.marza),
klienci_ax_all.sales_group,
klienci_ax_all.nazwa
FROM
sales_raport_all
INNER JOIN
klienci_ax_all
ON
sales_raport_all.konto=klienci_ax_all.konto_odbiorcy
WHERE
YEAR(from_date) = YEAR(CURDATE())
GROUP BY
sales_raport_all.from_date,
klienci_ax_all.sales_group
ORDER BY
sales_raport_all.from_date,
klienci_ax_all.sales_group");
$raw = array();
$dates = array();
while ($r = mysql_fetch_array($query)) {
$date = $r['from_date'];
if (!in_array($date, $dates)) $dates[] = $date;
$sales_group = $r['sales_group'];
$raw[$sales_group][$date] = intval($r['SUM(sales_raport_all.saldo_sprzedazy)']);
}
$data = array();
$data[0] = array('name' => "Date", 'data' => $dates);
foreach ($raw as $name => $d) {
$new_data = array('name' => $name, 'data' => array());
foreach ($dates as $date) {
$new_data['data'][] = isset($d[$date]) ? $d[$date] : 0;
}
$data[] = $new_data;
}
print json_encode($data);
in fiddle i use
chart3Options.series[0] = json[1];
...
is there a simple way to define all data in json? this data is variable and if i declare 11 variables and there will be only 7 then charts will not draw
JSON output for one date:
[{"name":"Date","data":["2014-01-01"]},{"name":"IN","data":[2580]},{"name":"KD","data":[5030]},{"name":"\u0141S","data":[12628]},{"name":"NN","data":[400]},{"name":"SG","data":[12979]},{"name":"TD","data":[15096]}]
// EDIT
i create new file:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'column',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'test',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'test'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
}
$.getJSON("test2.php", function(json) {
options.xAxis.categories = json[0]['category'];
options.series[0] = {};
options.series[0].name = json[0]['name'];
options.series[0].data = json[0]['data'];
chart = new Highcharts.Chart(options);
});
});
</script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
</head>
<body>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
and test2.php
<?php
$db_host = '******';
$db_user = '******';
$db_pass = '******';
$db_database = '******';
$link = mysql_connect($db_host,$db_user,$db_pass) or die('Nawiązanie połączenia z bazą danych nie było możliwe');
mysql_select_db($db_database,$link);
mysql_query("SET names UTF8");
$query = mysql_query("SELECT
sales_raport_all.from_date,
sales_raport_all.to_date,
sales_raport_all.konto,
SUM(sales_raport_all.saldo_sprzedazy),
SUM(sales_raport_all.wartosc_kosztowa),
SUM(sales_raport_all.marza),
klienci_ax_all.sales_group,
klienci_ax_all.nazwa
FROM
sales_raport_all
INNER JOIN
klienci_ax_all
ON
sales_raport_all.konto=klienci_ax_all.konto_odbiorcy
WHERE
YEAR(from_date) = YEAR(CURDATE())
GROUP BY
sales_raport_all.from_date,
klienci_ax_all.sales_group
ORDER BY
sales_raport_all.from_date,
klienci_ax_all.sales_group");
$result = array();
while($r = mysql_fetch_array($query)) {
$grupa = $r['sales_group'];
$datetime = $r['from_date'];
$result['name'][] = $datetime;
$result['category'][] = $grupa;
$result['data'][] = intval($r['SUM(sales_raport_all.saldo_sprzedazy)']);
}
$json = array();
array_push($json,$result);
print json_encode($json);
?>
JSON give me:
[{"name":["2014-01-01","2014-01-01","2014-01-01","2014-01-01","2014-01-01","2014-01-01"],"category":["IN","KD","\u0141S","NN","SG","TD"],"data":[2580,5030,12628,400,12979,15096]}]
Series looks greate but i dont know how to change category as in example http://jsfiddle.net/rubJS/
You can handle it in javascript. In other words, instead of defining variable for each <x,y> pair, return the data and let javascript construct the series.
For example, given your current output you can prepare X and Y values (in javascript) in separate arrays and write a function pushing these values into series. It can be done like this (using jQuery as an example):
function build_chart(x_values, y_values, options)
{
jQuery.each(x_values, function(item) {
options.xAxis.categories.push(x_values[item]);
});
var series = {
data: []
};
jQuery.each(y_values, function(item) {
series.data.push(parseInt(y_values[item]));
});
options.series.push(series);
chart = new Highcharts.Chart(options);
return chart;
}
Where variable options defines a chart template without series member (which is added by the above function)
EDIT
Following the edit in the question, here is the jsFiddle supporting it.
Note that the data in JSON is represented as array of arrays. First element in each array corresponds to the first category, second element in each array corresponds to the second category etc.
Apart from incorrect json format (which was mentioed) you need to push your dates as categorries in highcharts or use datetime type of axis, and then parse your date to timestamp.

Google Charts and MYSQL

i am new with PHP and Google charts. What i am trying to do it to make google charts with arduino data storred in a MYSL database. So far i insert data from arduino to mysql DB successfully but i face difficulties with the google charts.
Here is my PHP code:
<?php
$mysqli =mysqli_connect('localhost', 'root', '', 'Arduino');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: ".mysqli_connect_error();
}
$sql = mysqli_query($mysqli, 'SELECT * FROM analoog0');
if (!$sql) {
die("Error running $sql: " . mysql_error());
}
$results = array();
while($row = mysqli_fetch_assoc($sql))
{
$results[] = array(
'Date' => $row['Date'],
'Time' => $row['Time'],
'Temperature' => $row['Temperature']
);
}
$json = json_encode($results, JSON_PRETTY_PRINT);
echo $json;
?>
Here is the JSON output:
[ { "Date": "2013-10-24", "Time": "18:15:49", "Temperature": "24" },
{ "Date": "2013-10-24", "Time": "18:16:19", "Temperature": "24" },
{ "Date": "2013-10-24", "Time": "18:16:49", "Temperature": "24" },
{ "Date": "2013-10-24", "Time": "18:17:19", "Temperature": "23" } ]
And finally the HTM code:
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "localhost/Charts/chart_ver2.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.LineChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
When i run the HTM code nothing happens - the screen remains blank.
Any help, guidance or redirection will be highly appreciated!
Thanks in advance!!
You need to format the data correctly for the Visualization API. This should put your data in the correct format:
$results = array(
'cols' => array (
array('label' => 'Date', 'type' => 'datetime'),
array('label' => 'Temperature', 'type' => 'number')
},
'rows' => array()
);
while($row = mysqli_fetch_assoc($sql)) {
// date assumes "yyyy-MM-dd" format
$dateArr = explode('-', $row['Date']);
$year = (int) $dateArr[0];
$month = (int) $dateArr[1] - 1; // subtract 1 to make month compatible with javascript months
$day = (int) $dateArr[2];
// time assumes "hh:mm:ss" format
$timeArr = explode(':', $row['Time']);
$hour = (int) $timeArr[0];
$minute = (int) $timeArr[1];
$second = (int) $timeArr[2];
$results['rows'][] = array('c' => array(
array('v' => "Date($year, $month, $day, $hour, $minute, $second)"),
array('v' => $row['Temperature'])
));
}
$json = json_encode($results, JSON_NUMERIC_CHECK);
echo $json;
In your javascript, I would recommend rearranging the way you handle the AJAX query. There's nothing wrong per say with the way you are doing it, but I think this is a more elegant solution:
function drawChart() {
$.ajax({
url: 'localhost/Charts/chart_ver2.php',
dataType: 'json',
success: function (jsonData) {
// 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.LineChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}
});
}
You can't use the .responseText with a JSON response, as far as I know it only works for XML and Text.
$.ajax({
url: "localhost/Charts/chart_ver2.php",
dataType:"json",
async: false
}).responseText;
I would change it to:
$.ajax({
url: "localhost/Charts/chart_ver2.php",
dataType:"json",
async: false ,
success: function(data) {
jsonData = data;
}
});

Highcharts and php for a dynamic chart

I have been at this some time trying to get highcharts to chart some data returned by php. I have done many searches and nothing works. I can write the php to deliver the data however it needs to be but how do you get it to dynamically chart it?????
I can deliver it as:
[["1372875867","44.8782806"],["1372875885","46.2020226"]]
or
[[1372876686,44.0655823],[1372876693,43.3360596], etc ]
but how do I get the data from the php output into the dyname example they display?????
!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highstock Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
Highcharts.setOptions({
global : {
useUTC : false
}
});
// Create the chart
window.chart = new Highcharts.StockChart({
chart : {
renderTo : 'container',
events : {
load : function() {
// set up the updating of the chart eachsecond
var series = this.series[0];
setInterval(function() {
var x = (new Date()).getTime(),
y = Math.round(Math.random() * 100);
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
rangeSelector: {
buttons: [{
count: 1,
type: 'minute',
text: '1M'
}, {
count: 5,
type: 'minute',
text: '5M'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: false,
selected: 0
},
title : {
text : 'Live random data'
},
exporting: {
enabled: false
},
series : [{
name : 'Random data',
data : (function() {
// generate an array of random data
var data = [], time = (new Date()).getTime(), i;
for( i = -999; i <= 0; i++) {
data.push([
time + i * 1000,
Math.round(Math.random() * 100)
]);
}
return data;
})()
}]
});
});
</script>
</head>
<body>
<script src="../../js/highstock.js"></script>
<script src="../../js/modules/exporting.js"></script>
<div id="container" style="height: 500px; min-width: 500px"></div>
</body>
</html>
my current php is:
<?php
// include("$_SERVER[DOCUMENT_ROOT]/config/config.php");
include("adodb5/adodb.inc.php");
$connection = new COM("ADODB.Connection") or die("Cannot start ADO");
$result_set = $connection->Execute("
SELECT tag, TIME, value
FROM picomp
WHERE TIME >= '*-3m' AND tag = 'xxx:xx_xxx.xxx'
");
$result_count = 0;
// $labels = array();
while (!$result_set->EOF) {
$pidate = date("U", strtotime($result_set->fields[1]) );
if ($result_count <> 0){
print ",";
}else{
print "[";
}
print "[".$pidate.",".$result_set->fields[2]."]";
// array_push("{$result_set->fields[2]}");
$result_count = $result_count +1;
$result_set->MoveNext();
// echo "testing";
}
print "];";
You can use HighchartsPHP which is a wrapper for Highcharts, which basically allows you to write all that JS code in PHP. It's very useful and pretty simple to use.
HighchartsPHP on GitHub
Your timestamp should be multiplied by 1000, and both values should be numbers.
Please familair with soultion, how to prepare JSON, because you only print "as JSON", but it is not.
Take look at http://php.net/manual/en/function.json-encode.php where some examples are introduced.

Categories