I'm having trouble making a DataTable using the Javascript Literal Initializer (see
) ... when pulling the Javascript literal from an AJAX call to a .php resource on the server. Here is a toy example:
<html>
<head>
</head>
<body>
<script>
google.charts.load('current', {packages: ['corechart']});
$(document).ready(function(){
$("button").click(function(){
$.get( "./responder.php", {
foo: 'bar' // irrelevant
}, function( response ) {
console.log(response);
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(response);
var csv = google.visualization.dataTableToCsv(data);
console.log(csv);
}
});
});
});
</script>
<button>Make AJAX query</button>
</body>
</html>
<?php
$output = <<<'EOD'
{
cols: [{id: 'task', label: 'Employee Name', type: 'string'},
{id: 'startDate', label: 'Start Date', type: 'date'}],
rows: [{c:[{v: 'Mike'}, {v: new Date(2008, 1, 28), f:'February 28, 2008'}]},
{c:[{v: 'Bob'}, {v: new Date(2007, 5, 1)}]},
{c:[{v: 'Alice'}, {v: new Date(2006, 7, 16)}]},
{c:[{v: 'Frank'}, {v: new Date(2007, 11, 28)}]},
{c:[{v: 'Floyd'}, {v: new Date(2005, 3, 13)}]},
{c:[{v: 'Fritz'}, {v: new Date(2011, 6, 1)}]}
]
}
EOD;
header('Content-type: text/plain');
echo $output;
exit();
?>
The line
console.log(response);
.. prints the expected literal to the console, so it is being returned by the query.. But the line
var data = new google.visualization.DataTable(response);
.. throws an error :
Unhandled Promise Rejection: SyntaxError: JSON Parse error: Expected '}'
I'm sure it's something simple that I don't understand about javascript variables ('response' in my example), but it has me stumped.