简体   繁体   中英

How to dynamically populate data for google bar chart using json data returned from server

I'm using ajax to get json data from server to dynamically populate data for a google bar chart. I may have up to maximum 20 data points returned from the server or 0. I'm using php on server side to format data into json. The code works fine when I have 20 data points to return but I want to dynamically build up the data variable with the number of data points returned. I've tried different ways of filling in the array dynamically but couldn't get anything to work properly. Example of json data returned from server is:

date0: "05/Sep"
date1: "12/Sep"
date2: "17/Apr"
date3: "24/Apr"
date4: "01/May"
date5: "08/May"
date6: "15/May"
date7: "22/May"
rounds_found: 8
score0: "48"
score1: "48"
score2: "45"
score3: "45"
score4: "47"
score5: "49"
score6: "44"
score7: "50"

 $("#ajax_image").show();  // Show ajax spinner
    $.ajax({
        url: 'ajax.php',
        dataType: "json",
        data: { a: "getBarChart", player_id: $("#player_id").val() },
        success: function(data) { //called when successful  
            $("#ajax_image").hide();  // Hide ajax spinner          
            // Some raw data (not necessarily accurate)

            var data = google.visualization.arrayToDataTable([
              ['Date','Score' ],


                                // dynamically add data here

            ]);

            var options = {
              title : 'Last 20 Rounds Played',
              vAxis: {title: "Scores"},
              seriesType: "bars",
              series: {1: {type: "line"}}
            };

Elements in arrayToDataTable should look like this:
[String(data.date0), parseInt(data.score0)],
[String(data.date1), parseInt(data.score1)],
[String(data.date2), parseInt(data.score2)],
etc.

For dynamic loading you can use the following code

var bcData = new google.visualization.DataTable();

bcData.addColumn('string', 'Date');
bcData.addColumn('number', 'Score');

for (var i = 0; i < data.rounds_found; i++) {
    bcData.addRow([data['date' + i], parseInt(data['score' + i])]);
}

See example at jsbin without ajax code.

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