使用AJAX更新Google Charts值

I'm trying to update a Google Chart with data from a database using AJAX.

The updates should happen when I select an option.

However, it doesn't update anything...

Here's the chart:

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawChart);
  function drawChart() {
    var data = google.visualization.arrayToDataTable([

<?php include("chartdata.php");?>
]);

var options = {
    animation: {duration: 1000, easing: 'out', "startup": true},
    vAxis: {minValue: 0},
    pointSize: 4,
    pointShape: 'circle'
};

var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);

// FILTER CHART

$("#chart-selector option").click(function() {
    var selectname = $(this).val();
    $.ajax({
        url:"include/chartdata-filter.php",
        method:"POST",
        data:{select_name:selectname},
        dataType:"text",
        success:function(chart)
        {
            alert(chart); // WORKS
            chart.draw(google.visualization.arrayToDataTable([chart]), options); // DOESN'T WORK
        }
    });
});}

This is the select field. So when I select one it should update the chart:

<select id="chart-selector" name="select_name" onchange="chartSelect()">
<option>List Item 1</option>
<option>List Item 2</option>
</select>

When I select one of the options I get the output correctly in the alert. The output in the alert looks something like this (from chart.php):

['Date', 'Column 1', 'Column 2'],
['2016-10-01', 0, 0],
['2016-10-02', 1, 2],
['2016-10-03', 3, 4],
['2016-10-04', 5, 6],
['2016-10-05', 7, 8],
['2016-10-06', 9, 10]

Also, when I manually paste this data into the AJAX success function it works as well:

chart.draw(google.visualization.arrayToDataTable([
    ['Date', 'Column 1', 'Column 2'],
    ['2016-10-01', 0, 0],
    ['2016-10-02', 1, 2],
    ['2016-10-03', 3, 4],
    ['2016-10-04', 5, 6],
    ['2016-10-05', 7, 8],
    ['2016-10-06', 9, 10]]), options); // THIS WORKS

But obviously pasting it manually doesn't make any sense since I want to update the data onchange.

So to recap:

  1. I have select options.

  2. When I select one of the options the data should be pulled from the databse (WORKS).

  3. The data is pulled correctly in the alert, but it isn't updated in the chart. When I paste in the code manually it works onchange. So the problem is probably somewhere in here:

    chart.draw(google.visualization.arrayToDataTable([chart]), options);

Any suggestions?

Thanks in advance for anyone who has an idea!

I'm guessing it's because you're using dataType: 'text' so your chart variable is a string rather than an array (i.e. "[1, 2, 3]" instead of [1, 2, 3]). It's showing up correctly in the alert because the alert is displaying the contents of the string. You need to deserialize the array first. Try this:

var arr = JSON.parse("[" + ajaxResponse.replace(/'/g, '"').replace(/,$/g, '') + "]");
chart.draw(google.visualization.arrayToDataTable(arr), options);

Edit: Runcorn's answer includes an important detail I forgot to include. If the text returned from your ajax call doesn't have single quotes escaped with a \ or replaced with double quotes, it will fail.

Edit 2: Updated to include the relevant snippet for the working code. Here's a fiddle with it working correctly.

This is because you are passing test(String) to google.visualization.arrayToDataTable which instead requires array object. The AJAX response you get is a plain text which you would need to convert to Javascript array. Please follow the following steps to do so,

var resultantAjaxResponse="['Date', 'Column 1', 'Column 2'],['2016-10-01', 0, 0],['2016-10-02', 1, 2],['2016-10-03', 3, 4],['2016-10-04', 5, 6],['2016-10-05', 7, 8],['2016-10-06', 9, 10]";
//Convert String to JSON Parse-able form
resultantAjaxResponse = resultantAjaxResponse.replace(/'/g, '"');
//Convert to Javascript array
var arr = JSON.parse("[" + resultantAjaxResponse + "]");

You can now use the arr as,

chart.draw(google.visualization.arrayToDataTable([arr]), options); 

Please note that I haven't tested this code but this should fix the issue you are getting. Also, I would suggest you to return JSON instead of text in AJAX Response so that it would be more convenient and simple to map result to array.