How to create Google API line chart using PHP array / JSON? - php

I'm trying to create a simple Google line chart using their API. Hard coded, this works:
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales'],
['2010', 1000.31],
['2011', 1170.68],
['2012', 660]
]);
var options = {
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
However, I am trying to populate the chart values using data from MySQL. How do I get this to work?
$arr = array('Year' => 'Sales', '2010' => 1000.31, '2011' => 1170.68, '2012' => 660);
$chart_data = json_encode($arr);
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.DataTable(<?php echo $chart_data ?>);
var options = {
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
Basically, I am creating a PHP array from a MySQL result and trying to display its contents in the Google chart.

I know this is an old post but for anyone else who finds it I just wanted to post this which is the obvious answer:
https://developers.google.com/chart/interactive/docs/php_example
HTML:
<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: "getData.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.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
PHP:
<?php
// This is just an example of reading server side data and sending it to the client.
// It reads a json formatted text file and outputs it.
$string = file_get_contents("sampleData.json");
echo $string;
// Instead you can query your database and parse into JSON etc etc
?>
Sample data:
{
"cols": [
{"id":"","label":"Topping","pattern":"","type":"string"},
{"id":"","label":"Slices","pattern":"","type":"number"}
],
"rows": [
{"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]},
{"c":[{"v":"Onions","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Olives","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]}
]
}
To use a database, you would simply have to generate an array of columns and an array of rows and then json_encode them and return that instead of the .json file via PHP.

You can use the below link code and its in php and gd library and very simple to integrate with application.
http://www.kidslovepc.com/php-tutorial/php-dynamic-chart-plot.php.

Related

how to show a graph in each row in usgin googlechart(or chart.js etc)

I've been trying to display a graph in each row inside one page using Google chart but
I have no idea how to do that.
I get data from database when making a graph.
putting aside if this code below is right, here's my image.
#foreach ($titles as $title)
{{$title->title_name}}
<?php $getData = App\Graph::getNumber($title->id)?>
<div id="graph_bar{{$title->id}}" ></div> ←graph
#endforeach
<script type="text/javascript">
var barA= #json($getData->numberA);
var barB = #json($getData->numberB);
var barC= #json($getData->numberC);
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawchart);
function drawchart() {
var data = google.visualization.arrayToDataTable([
['', '', '', ''],
['', barA, barB , barC],
]);
var options = {
isStacked: true,
isStacked:'percent',
legend: {position: 'none'},
series: {
0:{color:'red'},
1:{color:'blue'},
2:{color:'grey'},
}
};
var chart = new google.visualization.BarChart(document.getElementById('graph_bar'));
chart.draw(data, options);
}
$(window).resize(function(){
drawchart();
});
</script>
1.Is it possible to do that(display a graph in each row) in the first place?
2.I'd like to get ID from HTML at javascript.
if anyone knows anything about this, I'd appreciate if if you would help me out.
thank you.

how can i transform my josn_encode data in array into google bar chart?

This is my json_encoded data
$encoded_data = json_encode($data);
echo $encoded_data;
[{"cols":"2017-09-02 11:01:55","rows":"1186.55"},{"cols":"2017-09-03 11:31:35","rows":"1311.45"},{"cols":"2017-09-06 15:22:38","rows":"90000.00"},{"cols":"2017-09-06 16:39:16","rows":"90000.00"},{"cols":"2017-09-06 16:40:09","rows":"630.00"},{"cols":"2017-09-06 17:25:26","rows":"1311.45"},{"cols":"2017-09-06 17:54:50","rows":"1311.45"},{"cols":"2017-09-07 09:28:57","rows":"1311.45"},{"cols":"2017-09-07 10:20:16","rows":"1575.00"},{"cols":"2017-09-07 10:22:28","rows":"1311.45"},{"cols":"2017-09-07 10:27:52","rows":"1311.45"},{"cols":"2017-09-07 10:34:00","rows":"1311.45"},{"cols":"2017-09-07 10:39:46","rows":"91575.00"},{"cols":"2017-09-07 10:40:48","rows":"91311.45"},{"cols":"2017-09-07 10:47:34","rows":"1575.00"},{"cols":"2017-09-07 10:50:53","rows":"1575.00"},{"cols":"2017-09-07 10:51:18","rows":"1575.00"}]
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load the Visualization API and the corechart package.
google.charts.load('visualization', '1', {'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() {
// Create the data table.
var jsonData = <?php echo $encoded_data; ?>
var data = new google.visualization.DataTable(jsonData);
// Set chart options
var options = {'title':'sales chart',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
It gives me an error the table has no columns.
the json is not in the correct format to create the data table directly,
see the structure of the JavaScript literal object described here...
if you don't want to change the format, then it can be transformed using javascript
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var jsonData = [{"cols":"2017-09-02 11:01:55","rows":"1186.55"},{"cols":"2017-09-03 11:31:35","rows":"1311.45"},{"cols":"2017-09-06 15:22:38","rows":"90000.00"},{"cols":"2017-09-06 16:39:16","rows":"90000.00"},{"cols":"2017-09-06 16:40:09","rows":"630.00"},{"cols":"2017-09-06 17:25:26","rows":"1311.45"},{"cols":"2017-09-06 17:54:50","rows":"1311.45"},{"cols":"2017-09-07 09:28:57","rows":"1311.45"},{"cols":"2017-09-07 10:20:16","rows":"1575.00"},{"cols":"2017-09-07 10:22:28","rows":"1311.45"},{"cols":"2017-09-07 10:27:52","rows":"1311.45"},{"cols":"2017-09-07 10:34:00","rows":"1311.45"},{"cols":"2017-09-07 10:39:46","rows":"91575.00"},{"cols":"2017-09-07 10:40:48","rows":"91311.45"},{"cols":"2017-09-07 10:47:34","rows":"1575.00"},{"cols":"2017-09-07 10:50:53","rows":"1575.00"},{"cols":"2017-09-07 10:51:18","rows":"1575.00"}];
var data = new google.visualization.DataTable();
data.addColumn('string', 'x');
data.addColumn('number', 'y');
jsonData.forEach(function (row) {
data.addRow([
row.cols,
parseFloat(row.rows)
]);
});
var options = {
title: 'sales chart',
width: 400,
height: 300,
chartArea: {
left: 140
}
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

PHP code and 2 While calling the same query

I need some help. I have some info in my db that I want to show in 2 charts using Google charts script.
Both scripts works but not when I use both scripts in a same page.. I bet is a problem with the while that are both equals since I need to show the same info. If I delete the first while the second loop start to work, but if no, the first just work.
The app works well because if I hardcode the values by hand and without the while works well both..
Here's the code:
<!-- First Chart start here: -->
<script type="text/javascript">
google.load("visualization", "1", {
packages: ["corechart"]
});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Formato', 'Cantidad'], <? php
//da problema si hay 2 while
while ($DatRDV = mysql_fetch_array($nrollos)) {
echo "['".$DatRDV['Formato'].
"',".$DatRDV['nRollos'].
"],";
} ?> ]);
var options = {
title: 'Formato de Rollos'
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<!-- Second chart start here: -->
<script type="text/javascript">
function drawVisualization() {
// Create and populate the data table.
var JSONObject = {
cols: [{
id: 'format',
label: 'Formato',
type: 'string'
}, {
id: 'cantidad',
label: 'Cantidades',
type: 'number'
}],
rows: [
<? php
while ($DatRDV = mysql_fetch_array($nrollos)) {
echo "{c:[{v: '".$DatRDV['Formato'].
"'}, {v: ".$DatRDV['nRollos'].
"}]},";
} ?> ]
};
var data = new google.visualization.DataTable(JSONObject, 0.5);
// Create and draw the visualization.
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, {
'allowHtml': true
});
}
google.setOnLoadCallback(drawVisualization);
</script>
try;
mysql_data_seek($nrollos,0);
before the 2nd loop

google.visualization.DataTable(<?php $jdata ?>)?

I am trying to produce a chart using Google visualization and php/mysql.
My data looks like this:
['RTI', 3],
['USAID', 1],
['Task Force', 1],
['DFID', 1],
['Other', 2]
If I print $jdata I get:
[{"Response":"Other","Count":"3"},{"Response":"RTI","Count":"3"},{"Response":"USAID","Count":"4"}]
which looks pretty close. Any advice?
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable(<?php $jdata ?>);
// Set chart options
var options = {'title':"Question1: I'm here to represent:",
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div1'));
chart.draw(data, options);
}
</script>
<?php $jdata ?> does nothing - you need to echo it - <?php echo $jdata ?>!

Google Visualization with PHP

I'm curious if I can inject PHP code to the datatable of google visualization instead of using JSON strings.
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows(
<?php
some PHP code that echoes the same format like this
[['Mushrooms', 3],['Onions', 1],['Olives', 1],['Zucchini', 1],['Pepperoni', 2]]
?>);
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
I'm trying to make events on google visualization. Any help/suggestions is very much appreciated. Thanks!
#scibuff has the right idea.
$my_array = array(
array('Mushrooms',3),
array('Onions',1),
array('Olives',1),
array('Zucchini',1),
array('Pepperoni',2)
);
echo json_encode( $my_array );
will give you [["Mushrooms",3],["Onions",1],["Olives",1],["Zucchini",1],["Pepperoni",2]]

Categories