简体   繁体   中英

Table has no columns when drawing google charts with JSON and Laravel from MySQL database

I have this situation where i execute a query and get the following table from the database:

GRAD_ACAD, subtotal
'DOC', 79
'LIC', 1
'MTR', 6

By following the example showed in the docs, i call my controller in the URL: ...

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

    function drawChart() {
      var jsonData = $.ajax({
          url: "{{URL::route('query01')}}",
          dataType:"json",
          async: false
          }).responseText;

      // Create our data table out of JSON data loaded from server.
      var data = new google.visualization.DataTable(jsonData);

      // Instantiate and draw our chart, passing in some options.
      var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
      chart.draw(data, {width: 400, height: 240});

...

When i open the view, i get the Table has no columns error. However, by using firebug i do see the json which looks like the following:

[{"GRAD_ACAD":"DOC","subtotal":79},{"GRAD_ACAD":"LIC","subtotal":1},{"GRAD_ACAD":"MTR","subtotal":6}]

I understand that i neeed to specify separately the column names and the rows. How do i do it? Or how do I fix this?

Simplest way is to format rightly your json to an array, then you can use google.visualization.arrayToDataTable

function right_format(data){
var arr = [];
for (var i = 0; i < data.length; i++) {
    var element = [];
    if (arr.length === 0){
        var columns = Object.keys(data[i]);
        arr.push(columns);
    };
    for (var j = 0; j < columns.length; j++){
        element.push(parseFloat(data[i][columns[j]]));
    };
    arr.push(element);
};
return arr;

};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM