Home > Backend Development > PHP Tutorial > How to Redraw a Google Chart Dynamically Using AJAX and PHP?

How to Redraw a Google Chart Dynamically Using AJAX and PHP?

Susan Sarandon
Release: 2024-12-05 14:02:17
Original
523 people have browsed it

How to Redraw a Google Chart Dynamically Using AJAX and PHP?

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):

  • Use PHP to fetch data from your database and handle the AJAX request.
  • Echo the data in JSON format that is compatible with Google's data table.
  • Ensure the appropriate column labels, types, and data structure.

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);
?>
Copy after login

2. AJAX Request in HTML/JavaScript:

  • Use jQuery AJAX to fetch data from the getdata.php endpoint and process the response.
  • On success, create a data table and draw the chart using the Google Visualization API.

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>
Copy after login

Notes:

  • Avoid using async: false in the AJAX request, as it can block the execution.
  • Move hAxis and vAxis options only once in the chart options object.
  • Ensure you are using the correct selector for the onchange event handler in the HTML.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template