Redraw Google Chart Based on User Input via AJAX Request
Problem:
You want to dynamically update a Google chart based on a selected table from a dropdown menu, but you're encountering an error when trying to fetch data via AJAX.
Solution:
To correctly redraw the chart using AJAX and external data, consider the following steps:
1. Data Preparation in PHP (getdata.php):
Example:
<?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); ?>
2. AJAX Request in HTML/JavaScript:
Example:
<script type="text/javascript"> google.load('visualization', '1', {callback: function() { $("#users").change(drawChart); function drawChart() { $.ajax({ url: 'getdata.php', data: 'q=' + $("#users").val(), dataType: 'json', success: function(responseText) { 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); } }); } }}); </script>
Notes:
The above is the detailed content of How to Redraw a Google Chart Dynamically Using AJAX and PHP?. For more information, please follow other related articles on the PHP Chinese website!