Background:
The goal is to update a Google chart based on user selection from a drop-down menu via AJAX, without having to reload the entire page.
Issue:
The initial attempt at the AJAX call is producing an error: $ is not defined. This is most likely due to the lack of a jQuery library reference in the code.
Solution:
To resolve the issue and enable AJAX functionality, follow these steps:
Include a jQuery Library Reference:
Use JSON Format for Data:
Remove Async: False Attribute:
Remove Inline Event Handlers:
Use hAxis and vAxis Only Once in Chart Options:
Example Code:
getdata.php:
<?php // ... Same database connection and query logic ... $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' => $row['Time']); $temp[] = array('v' => floatval($row['Wind_Speed'])); $temp[] = array('v' => floatval($row['Wind_Gust'])); $rows[] = array('c' => $temp); } $table['rows'] = $rows; echo json_encode($table); ?>
HTML / JavaScript:
<html> <head> <!-- ... Same as original code ... --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script> 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 }); } }); } }, packages: ['corechart'] }); </script> </head> <body>
Additional Notes:
The above is the detailed content of How can I dynamically update a Google Chart using AJAX based on user dropdown selection without page reload?. For more information, please follow other related articles on the PHP Chinese website!