Redraw google chart based on user input via AJAX request
recommend using php to get json in the form that google accepts
following is a full example for using ajax to get json data from php and draw a google chart
php
<?php
require("dbconnect.php");
$db = mysql_connect($server, $user_name, $password);
mysql_select_db($database);
$sqlQuery = "SELECT * FROM ".$_GET['q']." WHERE Date(Time + INTERVAL 10 HOUR) = Date(UTC_TIMESTAMP() + INTERVAL 10 HOUR)";
$sqlResult = mysql_query($sqlQuery);
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Time', 'type' => 'string'),
array('label' => 'Wind_Speed', 'type' => 'number'),
array('label' => 'Wind_Gust', 'type' => 'number')
);
while ($row = mysql_fetch_assoc($sqlResult)) {
$temp = array();
$temp[] = array('v' => (string) $row['Time']);
$temp[] = array('v' => (float) $row['Wind_Speed']);
$temp[] = array('v' => (float) $row['Wind_Gust']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
echo json_encode($table);
?>
and do not recommend using --> async: false
or inline event handlers --> <select name="users" onchange="drawVisualization(this.value)">
also, hAxis
and vAxis
should only appear once in chart options
html / javascript
<!DOCTYPE>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>
Wind Graph
</title>
<script src="http://www.google.com/jsapi"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
google.load('visualization', '1', {
// google-vis callback
callback: function () {
// add event listener to select element
$("#users").change(drawChart);
function drawChart() {
$.ajax({
url: 'getdata.php',
// use value from select element
data: 'q=' + $("#users").val(),
dataType: 'json',
success: function (responseText) {
// use response from php for data table
var data = new google.visualization.DataTable(responseText);
new google.visualization.LineChart(document.getElementById('visualization')).
draw(data, {
curveType: 'none',
title: 'Wind Chart',
titleTextStyle: {
color: 'orange'
},
interpolateNulls: 1
});
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown + ': ' + textStatus);
}
});
}
},
packages: ['corechart']
});
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<form>
<select id="users">
<option value="" selected disabled>Select unit:</option>
<option value="0001">0001</option>
<option value="0002">0002</option>
</select>
</form>
<div id="visualization" style="width: 100%; height: 400px;"></div>
</body>
</html>
Google chart does not redraw the chart based on a new Ajax filter
first, google's load
method only needs to be called once per page load.
afterwards, you can draw the chart, or charts, as many times as needed.
next, google's load
method will also wait on the page to load by default.
so we can use load
in place of jquery's ready
method.
recommend loading google first,
then make the call to get the data and draw the chart.
see following snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
function getData() {
$.ajax({
url: "datagen2_2.php",
dataType: "JSON"
}).done(function (result) {
drawChart(result);
});
}
$('.submit').click(getData);
getData();
function drawChart(result) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Gender');
data.addColumn('number', 'HowMany');
$.each(result, function (i, obj) {
data.addRow([obj.Gender, parseInt(obj.HowMany)]);
});
var piechart_options = {
title: 'Gender breakdown',
width: 470,
height: 270,
colors: ['#800080', '#b200ff']
};
var piechart = new google.visualization.PieChart(document.getElementById('piechart_div'));
piechart.draw(data, piechart_options);
}
});
How to use values from an ajax request in google charts?
recommend loading google
first, you can include the callback
directly in the load
statement
once loaded, then call ajax
see following working snippet, adjust as needed to get proper data,
and change error
to success
as the url isn't reachable from here...
google.charts.load('current', { callback: function () { var url = 'some url'; $.ajax({ dataType: 'json', url: url, error: function (data) { // <-- change 'error' to 'success' to run locally //for (var i = 0; i < data.length; i++) { //studentCount[data[i].month - 1].count = data[i].count; //}
var studentCount = [ { month:1, count:5 }, { month:2, count:3 }, { month:3, count:9 }, { month:4, count:0 }, { month:5, count:4 } ];
var data = google.visualization.arrayToDataTable([ ['Month', '2015'], ['January', studentCount[0].count], ['Febuary', studentCount[1].count], ['March', studentCount[2].count], ['April', studentCount[3].count], ['May', studentCount[4].count] // etc... ]);
var options = { hAxis: { title: 'Month' }, vAxis: { title: 'Number of Students' }, colors: ['#4285f4', '#db4437'] };
var chart = new google.charts.Line(document.getElementById('chart_div')); chart.draw(data, google.charts.Line.convertOptions(options));
} }); }, packages: ['line']});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="https://www.gstatic.com/charts/loader.js"></script><div id="chart_div"></div>
Redraw google after user input
I think what you're looking for is a DataView. A DataView is like an interface for changing how you view the data in a DataTable without actually changing the data.
var data = new google.visualization.DataTable();
var options = {
//set your options
}
//Load Your Data Here.
var view = new google.visualization.DataView(data);
view.setRows(view.getFilteredRows([{column: 0, minValue: minTime, maxValue: maxTime}]);
var chart = new google.visualization.MotionChart(document.getElementById('chart_div'));
chart.draw(view, options)
I also noticed that you declare a ChartRangeFilter control at the beginning. To bind that to a chart the both need to be part of a google.visulization.Dashboard. I was unable to determine if a MotionChart is capable of binding with a control, but you could give it a try and find out.
Redrawing a google chart for every modal pop up
the load
statement only needs to be called once per page
once the callback
fires the first time,
you can draw as many charts as needed
recommend loading google first, before anything else
if you have $(document).ready
somewhere, don't need it
you can rely on google's callback to know when the page is ready
recommend set up similar to following...
google.charts.load('current', {
callback: load_page_data,
packages: ['corechart']
});
function load_page_data(){
$('.modal').on('show.bs.modal', function () {
rid = $(this).prop('id') ;
console.log(rid);
$.ajax({
type: "POST",
url: 'getdata.php',
data: {'id': rid},
async: false,
success: function(data){
if(data){
chart_data = data;
drawChart(chart_data, "My Chart", "Data");
}
},
});
});
}
function drawChart(chart_data, chart1_main_title, chart1_vaxis_title) {
var chart1_data = new google.visualization.DataTable(chart_data);
var chart1_options = {
title: chart1_main_title,
vAxis: {title: chart1_vaxis_title, titleTextStyle: {color: 'red'}}
};
var chart1_chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart1_chart.draw(chart1_data, chart1_options);
}
note: you want to use the gstatic loader...
<script src="https://www.gstatic.com/charts/loader.js"></script>
not jsapi
<script src="https://www.google.com/jsapi"></script>
according to the release notes...
The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader from now on.
Refresh google visualization multiple charts on dashboard
Separated my chart code in a new page and reload the page when user clicks the refresh button.
Related Topics
"Connect Failed: Access Denied For User 'Root'@'Localhost' (Using Password: Yes)" from PHP Function
PHP Exec Command (Or Similar) to Not Wait For Result
How to Write a PHP Ternary Operator
PHP Error: Fatal Error: Constant Expression Contains Invalid Operations
Where Do We Use the Object Operator "-≫" in PHP
Speed Difference in Using Inline Strings VS Concatenation in PHP5
Best Solution to Protect PHP Code Without Encryption
PHP Function to Get the Subdomain of a Url
How to Embed PHP Code in JavaScript
Curl and PHP - How to Pass a Json Through Curl by Put,Post,Get
Get PHP to Stop Replacing '.' Characters in $_Get or $_Post Arrays
Simple Jquery, PHP and Jsonp Example
Force File Download With PHP Using Header()
Warning: MySQLi_Select_Db() Expects Exactly 2 Parameters, 1 Given
Laravel: Syntax Error or Access Violation: 1055 Error
Json_Encode() Escaping Forward Slashes