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;
}
});
Related
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.
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)}
I am trying to make a google ComboChart using data from json. the query that I am using is working fine in sql engine but the chart is not displaying.
This is the google chart script:
<div id="ranking_panel">
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['corechart']});
</script>
<script type="text/javascript">
function drawVisualization() {
// Some raw data (not necessarily accurate)
var json = $.ajax({
url: 'get_json_rank.php',
dataType: 'json',
async: false
}).responseText;
var data = new google.visualization.DataTable(json);
var options = {
title : 'Restaurant Ranking Stats',
vAxis: {title: "Business Growth"},
hAxis: {title: "Restaurants"},
seriesType: "bars",
series: {1: {type: "line"}}
};
var chart = new google.visualization.ComboChart(document.getElementById('rank_chart'));
chart.draw(data, options);
}
google.setOnLoadCallback(drawVisualization);
</script>
<div id="rank_chart"></div>
</div>
This is json code
<?php
$con = mysql_connect('localhost', 'root', '') or die('Error connecting to server');
mysql_select_db('db_MarkitBerry', $con);
$query = mysql_query('SELECT r_name, priority FROM tbl_restro ORDER BY priority DESC');
$table = array();
$table['cols'] = array(
array('label' => 'Priority', 'type' => 'string'),
array('label' => 'Restaurants', 'type' => 'string')
);
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$temp = array();
// each column needs to have data inserted via the $temp array
$temp[] = array('v' => $r['priority']);
$temp[] = array('v' => $r['r_name']);
$temp[] = array('v' => $r['r_name']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
echo $jsonTable;
?>
Debug!
From php/json side - use 'pre' tags and print_r function to see what is output via your request. Alternatively, install Firebug extension in Firefox, go to Network tab and set it to record every request - open the page, it will make ajax request - scroll down and see what is response.
In Javascript part, which calls up Google API - use console.log, and also use Firebug extension to see what is stored in every variable.
function drawVisualization() {
// Some raw data (not necessarily accurate)
var json = $.ajax({
url: 'get_json_rank.php',
dataType: 'json',
async: false
}).responseText;
**console.log(json);**
var data = new google.visualization.DataTable(json);
**console.log(data);**
var options = {
title : 'Restaurant Ranking Stats',
vAxis: {title: "Business Growth"},
hAxis: {title: "Restaurants"},
seriesType: "bars",
series: {1: {type: "line"}}
};
var chart = new google.visualization.ComboChart(document.getElementById('rank_chart'));
chart.draw(data, options);
}
You have two problems. First, you create two columns in your DataTable, but add three columns of data (though the third is a duplicate, and so it may just have been a copy error):
$temp[] = array('v' => $r['priority']);
$temp[] = array('v' => $r['r_name']);
$temp[] = array('v' => $r['r_name']); // <-- this is a duplicate, either add a third column or delete this line
Your second problem is that you are setting both column types to 'string', and most charts (including everything you can build with a ComboChart) require at least one 'number' column. Typically, you can build a chart with the first (domain) column as a string type, but all others must be number types.
I'm trying to draw a chart with google charts API. One column contains dates, the other one contains numbers.
This is the php page to get my data:
<?php
include 'core/init.php';
$result = mysql_query('SELECT amountDone, resultDate FROM result');
$table = array();
$table['cols'] = array(
array('label' => 'Done', 'type' => 'number'),
array('label' => 'Date', 'type' => 'date')
);
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$temp = array();
$temp[] = array('v' => (int)$r['amountDone']);
$temp[] = array('v' => $r['resultDate']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
?>
The json data returned is the following:
{"cols":[{"label":"Done","type":"int"},{"label":"Date","type":"date"}],"rows":[{"c": [{"v":1200},{"v":"2013-07-25"}]},{"c":[{"v":3600},{"v":"2013-07-26"}]}]}
In my main page I try to draw the chart with the following code:
<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: "get_json.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.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}
</script>
But I always get the following error (depends on the browser I use but they contain the same information I guess, this one is chrome):
Object 2013-07-25 has no method 'getTime
Anybody an idea what this could mean because I don't get a single other error
Thanks in advance!
changed my query to:
$result = mysql_query("SELECT DATE_FORMAT(resultDate, '%W, %D %M %Y') as Datum, SUM(amountDone) as AmountD, SUM(amountToDo) as AmountT
FROM result
GROUP BY resultDate");
and the type is now string. Works like a charm. :)
I am trying to create a Google line chart using their API and JSON.
Hard coded, this chart works:
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Date', 'Sales'],
['Jun 25', 12.25],
['Jun 26', 8.00],
['Jun 27', 20.50]
['Jun 28', 12.75]
]);
var options = {
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
However, trying to populate it using JSON, I can not get this to work:
<?php
$data = array();
$data["Date"] = "Sales";
$data["Jun 25"] = "12.25";
$data["Jun 26"] = "8.00";
$data["Jun 27"] = "20.50";
$data["Jun 28"] = "12.75";
$data = json_encode($data);
?>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(<?php echo $data; ?>);
var options = {
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
I'm obviously not encoding the array correctly. Google has an example page on how to populate their charts with JSON data here: https://developers.google.com/chart/interactive/docs/php_example
However, I could not find any examples for how to setup the JSON data with a simple line chart like this.
You're close.
$data = array(
array('Date', 'Sales'),
array('June 25', 12.25),
array('June 26', 8.00)
);
json_encode($data);
Output
[["Date","Sales"],["June 25",12.25],["June 26",8]]
See it in action.
Josh has already provided the correct answer. But in case you want to use google.visualization.DataTable instead of google.visualization.arrayToDataTable, first you can add columns separately then add json encoded php array:
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('string', 'Sales');
data.addRows(<?php echo $data; ?>);
while($fetch = sqlsrv_fetch_array( $result, SQLSRV_FETCH_BOTH))
{
$grid[$count]= $fetch['Hour'];
$grid1[$count]=$fetch['Revenue'];
$data[$count]=array($fetch['Hour'],$fetch['Revenue']);
$count++;
}
$num=$count;
$data[0] = array('Hours','Revenue');
for ($i=0; $i<($num+1); $i++)
{
$data[$i]=(array('c' => array(array('v' => (string)$grid[$i]), array('v' =>(int)($grid1[$i]) ), ) ));
}
$sample=array(array('type' => 'string', 'label' => 'date'),array('type' => 'number', 'label' => 'Amount'));
$table['cols'] = $sample;
$table['rows'] = $data;
echo (json_encode($table ));
This worked for me,If You format your json like this it will definitely work