How to populate Google chart API dynamically - php

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

Related

how to use mysql data on google charts

I am trying to create a bar chart using google charts and mysqli. But my code is not working when I try to insert php in the googlecharts it is no longer showing up on the webpage.
my code:
<!--GOOGLE CHARTS-->
<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':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
//PHP
<?php
if(isset($_GET['id'])) {
$ID= 'id';
$childId=$_GET['id'];
$rowId=$_GET['id'];
$chartsql = "SELECT `feis_entered`, `competition_level1`, `dance_name1`, `firstpl_score1`, `2ndpl_score1`, `3rdpl_score1` FROM `mark_cards1` WHERE id = '$rowId'";
$chartres = mysqli_query($con,$chartsql);
$chartrow=mysqli_fetch_array($chartres);
if($chartres){
$compName = '.$chartrow["feis_entered"].';
$compLvl = '.$chartrow["competition_level1"].';
$danceName = '.$chartrow["dance_name1"].';
$first = '.$chartrow["firstpl_score1"].';
$second = '.$chartrow["2ndpl_score1"].';
$third = '.$chartrow["3rdpl_score1"].';
}
}
?>
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Ranking');
data.addColumn('number', 'Score');
data.addRows([
['1st Place', <?php echo $first;?>],
['2nd Place', <?php echo $second;?>],
['3rd Place', <?php echo $third;?>]
]);
var data = google.visualization.arrayToDataTable([
['Element', 'Score', { role: 'style' }],
[ '1st Place', <?php echo $first;?>, 'color: #91b224',],
[ '2nd Place', <?php echo $second;?>, 'color: #91b224',],
[ '3rd Place', <?php echo $third;?>, 'color: #91b224',],
]);
// Set chart options
var options = {title:'<?php echo $compName - $compLvl - $danceName;?>',
colors: ['#91b224'],
is3D:true,
width:600,
height:550};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
first place, second place, and third place are the fields. CompName, compLvl, and danceName are the title.
EDIT picture of source code below
the chart values should be numbers instead of strings...
try removing the quotes...
from...
$first = '.$chartrow["firstpl_score1"].';
$second = '.$chartrow["2ndpl_score1"].';
$third = '.$chartrow["3rdpl_score1"].';
to...
$first = $chartrow["firstpl_score1"];
$second = $chartrow["2ndpl_score1"];
$third = $chartrow["3rdpl_score1"];

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)}

Google Bar chart labeling Dynamic data.How to add labels?

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);

Exact value not showing in google chart

I am using this code to call data from mysql and display it as a pie chart. But the chart not showing the exact value from column, whereas its showing as a percentage.
I want to display the exact value.
This is my code
<?php
$con=mysql_connect("localhost","pramir_feedback","feedback") or die("Failed to connect with database!!!!");
mysql_select_db("pramir_feedback", $con);
$sth = mysql_query("SELECT * FROM average");
$rows = array();
$flag = true;
$table = array();
$table['cols'] = array(
array('label' => 'data', 'type' => 'string'),
array('label' => 'average', 'type' => 'number')
);
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$temp = array();
$temp[] = array('v' => (string) $r['data']);
$temp[] = array('v' => (int) $r['average']);
$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: 'Average Data',
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.PieChart(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">fgfgfgfhiefkefejkfwefhfwjkefewfwf</div>
</body>
</html>
Here you can see the chart http://innovatrix.co.in/feedback_priyajit/graph.php
Thanks.
You need to ad the pieSliceText paramater, which takes the following values 'percentage','value','label' and 'none'
var options = {
title: 'Average Data',
is3D: 'true',
width: 800,
height: 600,
pieSliceText : 'value'};
For more details , click here
https://developers.google.com/chart/interactive/docs/gallery/piechart#Configuration_Options

Google charts: Object 2013-07-25 has no method 'getTime

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. :)

Categories