Alex17 Alex17 - 3 months ago 37
PHP Question

Redraw google chart based on user input via AJAX request

I have a google chart pulling data from my database that works as I want it to. Based on a get request in the URL it draws the data from the selected table.

I want make this chart update via ajax based on a selected table from a drop down menu. The part I can't break through on is getting the data to be responsive via ajax. I think the below code is close, but I'm getting the below error that I can't seem to get rid of.

getdata.php:22 Uncaught ReferenceError: $ is not defineddrawVisualization @ getdata.php:22onchange @ getdata.php:47

I tried removing the GET request from the getdata.php and hard coding a table in thinking that was the $not defined, but that didn't resolve the error.

Working Graph Code

<!DOCTYPE>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>
Wind Graph
</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['corechart']});
</script>
<script type="text/javascript">

function drawVisualization() {

var data = new google.visualization.DataTable();

<?php
require("dbconnect.php");

echo " data.addColumn('string', 'Time');";
echo " data.addColumn('number', 'Wind_Speed');";
echo " data.addColumn('number', 'Wind_Gust');";

$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);
while ($row = mysql_fetch_assoc($sqlResult)) {

echo " data.addRow(['{$row['Time']}', {v: {$row['Wind_Speed']}, f: '{$row['Wind_Speed']}' }, {v: {$row['Wind_Gust']}, f: '{$row['Wind_Gust']}' } ]); ";

}

?>

// Create and draw the visualization.
new google.visualization.LineChart(document.getElementById('visualization')).
draw(data, {curveType: "none",
title: "AU0001 Wind Chart",
titleTextStyle: {color: "orange"},
//width: 800, height: 400,
//vAxis: {maxValue: 10},
vAxis: {minValue: 0},
vAxis: {title: 'Wind Speed (Knots)'},
vAxis: {baseline: 0},
vAxis: {gridlines: {count: 10} },
vAxis: {title: "Wind Speed (Knots)", titleTextStyle: {color: "orange"}},
hAxis: {title: "Time", titleTextStyle: {color: "orange"}},
interpolateNulls: 1
}
);
}

google.setOnLoadCallback(drawVisualization);
</script>
</head>
<body>
<div id="visualization" style="width: 100%; height: 400px;"></div>
</body>
</html>


New code with AJAX request

<!DOCTYPE>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>
Wind Graph
</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['corechart']});
</script>
<script type="text/javascript">

function drawVisualization(num) {

var data = new google.visualization.DataTable(TableData);
var TableData = $.ajax({
url: "getdata.php",
data: "q="+num,
dataType:"json",
async: false
}).responseText;

// Create and draw the visualization.
new google.visualization.LineChart(document.getElementById('visualization')).
draw(data, {curveType: "none",
title: "Wind Chart",
titleTextStyle: {color: "orange"},
//width: 800, height: 400,
//vAxis: {maxValue: 10},
vAxis: {minValue: 0},
vAxis: {title: 'Wind Speed (Knots)'},
vAxis: {baseline: 0},
vAxis: {gridlines: {count: 10} },
vAxis: {title: "Wind Speed (Knots)", titleTextStyle: {color: "orange"}},
hAxis: {title: "Time", titleTextStyle: {color: "orange"}},
interpolateNulls: 1
}
);
}

// google.setOnLoadCallback(drawVisualization);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<form>
<select name="users" onchange="drawVisualization(this.value)">
<option value="">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>


getdata.php code

<?php
require("dbconnect.php");

echo " data.addColumn('string', 'Time');";
echo " data.addColumn('number', 'Wind_Speed');";
echo " data.addColumn('number', 'Wind_Gust');";

$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);
while ($row = mysql_fetch_assoc($sqlResult)) {

echo " data.addRow(['{$row['Time']}', {v: {$row['Wind_Speed']}, f: '{$row['Wind_Speed']}' }, {v: {$row['Wind_Gust']}, f: '{$row['Wind_Gust']}' } ]); ";

}

?>

Answer

i would recommend returning json from the php in the form that google accepts

getdata.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>
Comments