JQuery / AJAX with JavaScript Literal Initializer

15 views
Skip to first unread message

Michael Axtell

unread,
Oct 20, 2021, 4:21:22 PM10/20/21
to Google Visualization API
I'm having trouble making a DataTable using the Javascript Literal Initializer (see https://developers.google.com/chart/interactive/docs/datatables_dataviews#javascriptliteral)  ... when pulling the Javascript literal from an AJAX call to a .php resource on the server. Here is a toy example:

index.html
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
  <script src="https://www.gstatic.com/charts/loader.js"></script>
</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>


responder.php
<?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.

Any suggestions?

Reply all
Reply to author
Forward
0 new messages