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.
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>
how do i pass an array from php to jquery
both are in same file , i just have an array named $array2 with data that will be used to make graph
below code is using chartdata but i want to use variable from my php script
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var chart;
var chartData = [{
student: 5,
marks: 0},
{
student: 8,
marks: 50},
{
student: 10,
marks: 100}];
AmCharts.ready(function() {
// SERIAL CHART
chart = new AmCharts.AmSerialChart();
chart.dataProvider = chartData;
chart.categoryField = "marks";
chart.startDuration = 1;
// AXES
// category
var categoryAxis = chart.categoryAxis;
categoryAxis.labelRotation = 90;
categoryAxis.gridPosition = "student";
// value
// in case you don't want to change default settings of value axis,
// you don't need to create it, as one value axis is created automatically.
// GRAPH
var graph = new AmCharts.AmGraph();
graph.valueField = "student";
graph.balloonText = "[[category]]: [[value]]";
graph.type = "column";
graph.lineAlpha = 0;
graph.fillAlphas = 8.4;
chart.addGraph(graph);
chart.write("chartdiv");
});
</script>
you can use json data to pass php to jquery.
in php
$php_data = json_encode($your_php_data_in_array);
assigning to jquery
var data = <?php echo $php_data ;?>
getting the value in jquery
var chart_data_arr = json_decode(data);
now you have the data in array in jquery.
The simplest (and not necessarily the most scure/efficient/modular/blah blah) possible way you can just dump it using json_encode
var chartData = [{
student: 5,
marks: 0},
{
student: 8,
marks: 50},
{
student: 10,
marks: 100}];
//Instead
var chartData=<?php echo json_encode($chartdata)?>
Alternately, you would pass it using a json action that will render the json at a certian link and use jquery to query this url and then generate the chart with that data.
To use php data in javascript use:-
var javascriptVariable = <?php echo json_encode($php_array); ?>;
So javascriptVariable would become an object/array as per your php data.
Try this :
<?php
$your_php_array = array(.....);
?>
var chartData = <?php json_encode($your_php_array)?>;
ref: http://php.net/manual/en/function.json-encode.php
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 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 ?>!
I've got a problem with the visualization of data with google's charts api after an ajax call.
First I made an ajax call and fetched a json object. After that I want to extract some data out of the json and draw a gauge chart. Getting the json and extracting the data works fine, but when I try to load the chart, the body gets removed and I get a blank/white screen. Does anyone knows what I am doing wrong? I also tried to hard code values for the chart instead of taking the json values (but kept the ajax call before loading the chart), but it didn't work neither.
function loadStats(){
var http = getRequestObject();
var city = "berlin";
http.open("GET", "getTwitterSentiments.php?city="+city, true);
http.onreadystatechange=function() {
getStatistic(http)
};
http.send(null);
}
function getStatistic(request) {
if ((request.readyState == 4) && (request.status == 200)) {
var data = request.responseText;
var JSONStats = eval("(" + data + ")");
loadGauge(JSONStats.sentiment_index);
}
function loadGauge(sentiment){
google.load('visualization', '1', {packages:['gauge']});
google.setOnLoadCallback(drawGauge);
function drawGauge() {
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Test', sentiment]
]);
var options = {
width: 100,
height: 100,
redFrom: 0,
redTo: 45,
yellowFrom: 45,
yellowTo: 55,
greenFrom: 55,
greenTo: 100,
minorTicks: 10
};
var chart = new google.visualization.Gauge(document.getElementById('testgchart'));
chart.draw(data, options);
}
}
Try using the callback feature of google.load() function.
For instance, for your code, try the following:
function loadGauge(sentiment){
google.load('visualization', '1.0', {'packages':['gauge'], 'callback': drawGauge});
}
function drawGauge(){
...
chart.draw(data, options);
}
For more information, check the 'Dynamic loading' section of Google Loader Developer Guide:
https://developers.google.com/loader/#Dynamic
If i understand correctly, calling loadGauge() multiple times will not cause multiple trips to Google servers to load the required APIs, but just once.
I guess your element testgchart is not load in the DOM yet, your code should work.
I made an example from your code :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://www.google.com/jsapi"></script>
<script>
function loadGauge(val){
google.load('visualization', '1', {packages:['gauge']});
google.setOnLoadCallback(drawGauge);
function drawGauge() {
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Test', val],
]);
var options = {
width: 100,
height: 100,
redFrom: 0,
redTo: 45,
yellowFrom: 45,
yellowTo: 55,
greenFrom: 55,
greenTo: 100,
minorTicks: 10
};
var chart = new google.visualization.Gauge(document.getElementById('average'));
chart.draw(data, options);
}
}
</script>
</head>
<body>
<div id="average"></div>
<script>loadGauge(99)</script>
</body>
</html>
But it doesn't work if you delete this line <script>loadGauge(99)</script> and replace the body tag with <body onload="loadGauge(99)">. Your probably doing something similar.
If your sure the element testgchart is present then put a log in loadGauge and tell me if it really get called by getStatistic.