benedikt.r benedikt.r -4 years ago 125
Ajax Question

Google Charts - Not drawing Chart - Data table is not defined

I set an Interval with Ajax for my Google Chart but the Chart isnt being drawn. I only get the message: "Data table is not defined." every 5 seconds. Picture of the Meessage.

Google Chart Source:

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">

// Load the Visualization API and the piechart package.
google.charts.load('current', {'packages':['corechart']});

// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
setInterval(drawChart, 5000);

function load_page_data(){
$.ajax({
url: 'getTemp.php',
type: 'get',
success: function (json) {
var data = new google.visualization.DataTable(<?php echo json_encode($table); ?>);


var options = {
title: 'Raspberry:',
curveType: 'function',
'height':400
};
},
});
}
function drawChart() {
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw();

}

</script>


PHP File that gets the Data from MySQL:

$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

try {
$result = $conn->query('SELECT *
FROM Device_Data ');



$rows = array();
$table = array();
$table['cols'] = array(array('label' => 'Timestamp', 'type' => 'string'),array('label' => 'Temperature', 'type' => 'number'),array('label' => 'Humidity', 'type' => 'number'));

foreach($result as $r) {

$data = array();
$data[] = array('v' => (string) $r['Timestamp']);
$data[] = array('v' => (int) $r['Temperature']);
$data[] = array('v' => (int) $r['Humidity']);

$rows[] = array('c' => $data);

}

$table['rows'] = $rows;

} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}

try {
$result2 = $conn->prepare("SELECT 'Temperature','Humidity', 'Timestamp' from Device_Data;");

$result2->execute();

} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}

?>

Answer Source

in chart.draw(); u have to provide the datatable and options

chart.draw(dataTable, options);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download