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 ?>!
Related
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>
This is two questions in one, the actual state of my code is this:
<script type="text/javascript">
init_ui();
function init_ui() {
$("[rel='tooltip']").tooltip();
$(".ajax_link").live("click",function(){
id = $(this).attr("id");
jQuery("#ajax_div").html('<img src="../../../../bundles/donepunctis/img/loading.gif" alt="loading...">');
jQuery.ajax({
url: '<?= $view['router'] -> generate('done_punctis_ajax_detail_data_url'); ?>' + '?id=' + id,
success:function(result){
jQuery("#ajax_div").html('');
//alert(data);
chart.draw(data, options);
}
});
})
}
var data;
var options;
var chart;
// 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.
data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Mushrooms', 3],
['Onions', 1],
['Olives', 1],
['Zucchini', 1],
['Pepperoni', 2]
]);
// Set chart options
options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
chart = new google.visualization.PieChart(document.getElementById('ajax_div'));
}
</script>
At the moment im just ignoring the return from the ajax call, using the data to the chart somministrated hard coded on the var data.
how should look my echo on the php side to return the same value I'm using right now, but passed from the ajax return?
this code is working fine the first time, but if try to click again ajax_link the ajax call is fired but the google chart code doesn't do anything. Why is that?
This code is working fine the first time, but if try to click again ajax_link the ajax call is fired but the google chart code doesn't do anything. Why is that?
Look at the success callback from your $.ajax call:
jQuery.ajax({
url: '<?= $view['router'] -> generate('done_punctis_ajax_detail_data_url'); ?>' + '?id=' + id,
success:function(result){
jQuery("#ajax_div").html('');
chart.draw(data, options);
}
});
You are calling chart.draw(data, options);, which simply redraws the chart with the data you last populated it with.
You probably want to call drawChart and pass in the new data:
jQuery.ajax({
url: '<?= $view['router'] -> generate('done_punctis_ajax_detail_data_url'); ?>' + '?id=' + id,
success:function(result){
jQuery("#ajax_div").html('');
drawChart(data);
}
});
Then in drawChart you can populate the chart with your new data:
function drawChart(myData) {
// Create the data table.
data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
if(myData) {
// TODO: add rows based on myData
} else {
data.addRows([
['Mushrooms', 3],
['Onions', 1],
['Olives', 1],
['Zucchini', 1],
['Pepperoni', 2]
]);
}
...
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.
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]]
I have some data and want to create some dynamic charts. I have looked on Google visualisation api .. It looks great but the problem is I am not very familiar with it. Any ideas, how I can set the data.setValue from mysql data.
<script type='text/javascript'>
google.load('visualization', '1', {'packages': ['geomap']});
google.setOnLoadCallback(drawMap);
function drawMap() {
var data = new google.visualization.DataTable();
data.addRows(6);
data.addColumn('string', 'Country');
data.addColumn('number', 'Popularity');
data.setValue(0, 0, 'Germany');
data.setValue(0, 1, 200);
data.setValue(1, 0, 'United States');
data.setValue(1, 1, 300);
data.setValue(2, 0, 'Brazil');
data.setValue(2, 1, 400);
data.setValue(3, 0, 'Canada');
data.setValue(3, 1, 500);
data.setValue(4, 0, 'France');
data.setValue(4, 1, 600);
data.setValue(5, 0, 'RU');
data.setValue(5, 1, 700);
var options = {};
options['dataMode'] = 'regions';
var container = document.getElementById('map_canvas');
var geomap = new google.visualization.GeoMap(container);
geomap.draw(data, options);
};
</script>
I can create chart using some other methods but just interested in using Google Visualisation API.
Thanks.
Update:
Have a look at how you can add data to the chart. You have the possibility to add data in JSON.
The only thing you have to do is to prepare a corresponding PHP array. Then you can serialize this array and set the data. E.g.
<?php
// $data is an array and already has the correct structure...
$jdata = json_encode($data);
?>
<!-- later ... -->
<script type='text/javascript'>
google.load('visualization', '1', {'packages': ['geomap']});
google.setOnLoadCallback(drawMap);
function drawMap() {
var data = new google.visualization.DataTable(<?php echo $jdata ?>);
var options = {};
options['dataMode'] = 'regions';
var container = document.getElementById('map_canvas');
var geomap = new google.visualization.GeoMap(container);
geomap.draw(data, options);
};
</script>
I recommend to read the documentation / API reference. I basically found this just by searching...
Without further information we cannot give a specific answer but a general approach is:
Assuming that you already fetched the records from your DB in a result set $results than you can just loop over it:
<?php foreach($results as $row): ?>
data.setValue(<?php echo $row['column1']; ?>, <?php echo $row['column2']; ?>);
// depends on what type of char you want to create, on your actual data etc.
<?php endforeach; ?>
i recommend http://pchart.sourceforge.net/ pchart for graphing. it works perfectly.