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.
Related
I need help with drawing chart that is auto updating. I currently have two php files, one which gets data from MySQL database and turns it into JSON get_json.php, and the other that turns gotten data into chart, linechart.php.
Chart appears, but there is nothing on it, and both axis go from 0 to 1, and I need x axis to be TimesStamp column from database.
Here are codes:
get_json.php
<?php
$con = mysqli_connect('localhost', 'u644759843_miki', 'plantaze2020!') or die('Error connecting to server');
mysqli_select_db('u644759843_plantazeDB', $con);
// write your SQL query here (you may use parameters from $_GET or $_POST if you need them)
$query = mysqli_query('SELECT `FlowRate`, `ProductPurity`, `TimesStamp` FROM `Precizno ProductPurity` ORDER BY TimesStamp DESC LIMIT 10');
$table = array();
$table['cols'] = array(
/* define your DataTable columns here
* each column gets its own array
* syntax of the arrays is:
* label => column label
* type => data type of column (string, number, date, datetime, boolean)
*/
// I assumed your first column is a "string" type
// and your second column is a "number" type
// but you can change them if they are not
array('label' => 'FlowRate', 'type' => 'number'),
array('label' => 'ProductPurity', 'type' => 'number'),
array('label' => 'TimesStamp', 'type' => 'number')
);
$rows = array();
while($r = mysqli_fetch_assoc($query)) {
$temp = array();
// each column needs to have data inserted via the $temp array
$temp[] = array('v' => (int) $r['ProductPurity']);
$temp[] = array('v' => (int) $r['FlowRate']);
$temp[] = array('v' => (int) $r['TimesStamp']); // typecast all numbers to the appropriate type (int or float) as needed - otherwise they are input as strings
// insert the temp array into $rows
$rows[] = array('c' => $temp);
}
// populate the table with rows of data
$table['rows'] = $rows;
// encode the table as JSON
$jsonTable = json_encode($table);
// set up header; first two prevent IE from caching queries
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
// return the JSON data
echo $jsonTable;
?>
linechart.php
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script>
// 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() {
//AJAX Call is compulsory !
var jsonData = $.ajax({
url: "/nitrogengenerator/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);
var options = {
title: 'Nitrogen Generator',
is3D: 'true',
width: 800,
height: 600
};
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<script type="text/javascript" src="jQuery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// First load the chart once
drawChart();
// Set interval to call the drawChart again
setInterval(drawChart, 5000);
});
</script>
<!-- Kraj koda za grafik -->
</head>
<body>
<div id="chart_div"> </div>
</body>
</html>
I am pulling data from a mysql database in a PHP script and using google charts to display the data graphically. It worked fine when using a pie or bar chart with only 2 variables to deal with. Now I want to use a ComboChart. I have 4 fields in a table: Name, Date, Quanity, Cost. I want to have a ComboChart where along the x-axis is the Date, a bar graph will represent the Quantity, and a line graph will represent the Cost.
Here is the code I have so far. How can I go about doing this? In the drawChart() function there's no explicit order to what is on the x or y axis so how do I know which of my data is being displayed where? Does that depend on what order you select the data in during the mysqli_query?
// host, username, password and dbname are already declared
$conn = mysqli_connect($host, $username, $password);
if ($conn->connect_error) {
die("Could not connect: " . mysql_error()) . "<br>";
}
mysqli_select_db($conn, $dbname);
$qresult = mysqli_query($conn, "SELECT * FROM Scrap");
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Date', 'type' => 'string'),
array('label' => 'Quantity', 'type' => 'number'),
array('label' => 'Cost', 'type' => 'number')
);
$rows = array();
while ($r = $qresult->fetch_assoc()) {
$temp = array();
$temp[] = array('v' => (string) $r['Date']);
// Values of each slice
$temp[] = array('v' => (int) $r['Quantity']);
$temp[] = array('v' => (float) $r['Cost']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
?>
<html>
<head>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.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() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var options = {
title: 'YTD Controllable Scrap Costs',
seriesType:'bars',
series:{2: {type: 'line'}}
// width: 800,
// height: 600
};
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--this is the div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
So I tested around and I found out that the first column is the x-axis and the 2nd, 3rd, 4th, etc go on the y-axis. The reason the bar AND line graph weren't showing up was because in my drawChart() function, where it says: series:{2: {type: 'line'}}, the number 2 refers to the 3rd field for the y-axis since it is zero-indexed. I didn't have a 3rd field for the y-axis, so I switched it to series:{1: {type: 'line'}} and now I get a bar graph and a line graph.
I am creating a Google charts bar chart! The data comes from MySQL, using JSON and PHP.
All I would like is to put labels at the end of Bar charts. Because data are dynamic, i found it difficult.
<?php
$sth = mysql_query("select * from table");
$rows = array();
//flag is not needed
$flag = true;
$table = array();
$table['cols'] = array(
array('label' => 'Stats', 'type' => 'string'),
array('label' => 'Value', 'type' => 'number')
);
$rows = array();
while($r = mysql_fetch_assoc($sth))
{
$temp = array();
$temp[] = array('v' => (string) $r['Stats']);
$temp[] = array('v' => (int) $r['Value']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
?>
<script type="text/javascript">
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);
var options = {
legend: {position: 'none'},
bar: {groupWidth: "85%"},
colors:['#4A9218'],
hAxis: {
viewWindowMode: 'explicit',
viewWindow: {
max: 400,
min: 0,
},
gridlines: {
count: 10,
}
}
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<!--this is the div that will hold the pie chart-->
<div id="chart_div" style="width:100%; height:200px"></div>
Outcome :
Bar chart with no labeling
Outcome I am looking for:
Bar chart with labeling at the end on the right
First, add JSON_NUMERIC_CHECK to your json_encode call, as MySQL outputs numbers as strings, and inputting numbers as strings can cause problems with some charts:
$jsonTable = json_encode($table, JSON_NUMERIC_CHECK);
If you want to add the data values as annotations on the bars, the easiest way is to create a DataView that includes a calculated 'annotation' role column that takes its data from the value column and stringifies it:
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
type: 'string',
role: 'annotation',
sourceColumn: 1,
calc: 'stringify'
}]);
Then use the view to draw your chart instead of the DataTable:
chart.draw(view, options);
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;
}
});
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. :)