javascriptgoogle-pie-chart

JavaScript pie chart functions and callbacks displaying only last elements in database


I am trying to create dynamic number of pie charts depending on how many question I have in my quiz but, the function that creates the chart is in for loop only 1 pie chart is displayed with data which are last in database.

var l = 0;
for (var j in quizs[i].quests) {
if (val == quizs[i].quests[j]["quizId"]) {
    l = l + 1;
    google.charts.load('current', {
        'packages': ['corechart']
    });
    google.charts.setOnLoadCallback(drawChart);
    alert("before++" + quizs[i].quests[j]["question"]);

    function drawChart() {

        alert("in++" + quizs[i].quests[j]["question"]);
        var data = google.visualization.arrayToDataTable([
            ['Task', 'Hours per Day'],
            ['Work', 11],
            ['Eat', 2],
            ['Commute', 2],
            ['Watch TV', 2],
            ['Sleep', 7]
        ]);
        var options = {
            title: 'My Daily Activities'
        };
        var chart = new google.visualization.PieChart(document.getElementById(l));
        chart.draw(data, options);
    }
}
}

for example alert("in++" + quizs[i].quests[j]["question"]); is the last element in database, any answer is appreciated.


Solution

  • google.charts.setOnLoadCallback must support only one callback. You should put your loop inside of the callback instead of trying to load a new Google Charts API for each loop iteration:

    google.charts.setOnLoadCallback(() => {
      var l = 0;
      for (var j in quizs[i].quests) {
        if (val == quizs[i].quests[j]["quizId"]) {
          l = l + 1;
          var data = google.visualization.arrayToDataTable([
            ['Task', 'Hours per Day'],
            ['Work', 11],
            ['Eat', 2],
            ['Commute', 2],
            ['Watch TV', 2],
            ['Sleep', 7]
          ]);
    
          var options = {
            title: 'My Daily Activities'
          };
          var chart = new google.visualization.PieChart(document.getElementById(l));
          chart.draw(data, options);
        }
      }
    });
    
    google.charts.load('current', {
      packages: ['corechart']
    });