i am trying to display google charts with data from a MYSQL database. It work's when i am using two seperate files (php/js) but i want to process the data in one file.
Heres what i got:
$table = array();
$table['cols'] = array(
array('label' => 'Date', 'type' => 'string'),
array('label' => 'Meter', 'type' => 'number')
);
$rows = array();
$select->execute();
while ($result = $select->fetch(PDO::FETCH_ASSOC)) {
$timestamp = strtotime($result['date']);
$date = date("d.m.Y - H:i", $timestamp);
$temp = array();
$temp[] = array('v' => $date);
$temp[] = array('v' => $result['meter']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$json = json_encode($table);
echo $json;
?>
<html>
<head>
<script type="text/javascript" src="../assets/js/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
dataType: "json",
async: true
}).responseText;
alert(jsonData);
var data = new google.visualization.DataTable(jsonData);
var chart = new google.visualization.LineChart(document.getElementById('chart_div2'));
chart.draw(data, {width: 1000, height: 240});
}
</script>
</head>
<body>
<hr class="major" />
<div id="chart_div2"></div>
</body>
</html>
The PHP data gets encoded properly but i dont know how to "send" the data to the javascript part. Is it possible to receive the JSON data in the same file?
When i change async: true
to false
, it just displays the code from the whole page, with true
it displays undefined
.
Kind regards, Skar
</div>