1

I am trying to display one chart per question that is loaded if the answers I get from server are numbers. The problem is that I am only able to display a chart on the last question. Any idea of how to display one chart per question? Thanks in advance.

function chooseSurv(number, name) {
  var j = number;
  var question = new Array();
  question = survQuestions[j];
  var questionType = new Array();
  questionType = survType[j];
  var outputans = "";
  var outputchart = "";
  var SurveyAnswer = Parse.Object.extend("someclass);
  var query = new Parse.Query(SurveyAnswer); query.descending("createdAt"); query.include("author"); query.include("survey"); query.equalTo("survey", somestring); query.find({
    success: function(results) {
      for (var u = 0; u < question.length; u++) {
        var questions = question[u];
        outputans += '<div id="ansbox">';
        if (questionType[u] / 1) {
          var divid = "chart_div" + j + u;
          console.log(divid);
          outputans += '<div id="' + divid + '" class="chart-box"></div>';
          outputans += '</div>';
          for (var k in results) {
            var answer = results[k].get("data")[u];
            var author = results[k].get("author");
            var name = author.get("name");
            outputans += '<h4>' + name + '</h4>';
            outputans += '<p>' + answer + '</p>';
            outputans += '</div>';
          }
          // Load the Visualization API and the corechart package.
          google.charts.load('current', {
            'packages': ['corechart']
          });
          // Set a callback to run when the Google Visualization API is loaded.
          google.charts.setOnLoadCallback(drawChart);
          // Callback that creates and populates a data table,
          // instantiates the pie chart, passes in the data and
          // draws it.
          function drawChart() {
            // Create the data table.
            var data = new google.visualization.DataTable();
            data.addColumn('string', 'Topping');
            data.addColumn('number', 'Slices');
            data.addRows([
              ['Mushrooms', 3],
              ['Onions', 1],
              ['Olives', 1],
              ['Zucchini', 1],
              ['Pepperoni', 2]
            ]);
            // Set chart options
            var options = {
              'title': 'How Much Pizza I Ate Last Night',
              'width': 400,
              'height': 300
            };
            // Instantiate and draw our chart, passing in some options.
            var chart = new google.visualization.PieChart(document.getElementById(divid));
            chart.draw(data, options);
            console.log(divid);
          }
        } else {
WhiteHat
  • 59,912
  • 7
  • 51
  • 133
Olekern
  • 87
  • 2
  • 10

1 Answers1

0

the real answer is here --> JavaScript closure inside loops – simple practical example...

basically, divid changes with each loop. and when finished, points to the last version of u.
which the chart function then tries to use...


several ways to avoid, but a little restructuring should do the trick...

first: google.charts.load and setOnLoadCallback were designed to be run once per page load

not every time a chart should be drawn

try loading google first, then continue with the rest

removing the closures, or functions, from success -- should correct the problem

see following snippet...

// Load the Visualization API and the corechart package.
google.charts.load('current', {
  // Set a callback to run when the Google Visualization API is loaded.
  'callback': chooseSurv,
  // Set packages to use
  'packages': ['corechart']
});

function chooseSurv(number, name) {
  var j = number;
  var question = new Array();
  question = survQuestions[j];
  var questionType = new Array();
  questionType = survType[j];
  var outputans = "";
  var outputchart = "";
  var SurveyAnswer = Parse.Object.extend("someclass);
  var query = new Parse.Query(SurveyAnswer); query.descending("createdAt"); query.include("author"); query.include("survey"); query.equalTo("survey", somestring); query.find({
    success: function(results) {
      for (var u = 0; u < question.length; u++) {
        var questions = question[u];
        outputans += '<div id="ansbox">';
        if (questionType[u] / 1) {
          var divid = "chart_div" + j + u;
          console.log(divid);
          outputans += '<div id="' + divid + '" class="chart-box"></div>';
          outputans += '</div>';
          for (var k in results) {
            var answer = results[k].get("data")[u];
            var author = results[k].get("author");
            var name = author.get("name");
            outputans += '<h4>' + name + '</h4>';
            outputans += '<p>' + answer + '</p>';
            outputans += '</div>';
          }

          var data = new google.visualization.DataTable();
          data.addColumn('string', 'Topping');
          data.addColumn('number', 'Slices');
          data.addRows([
            ['Mushrooms', 3],
            ['Onions', 1],
            ['Olives', 1],
            ['Zucchini', 1],
            ['Pepperoni', 2]
          ]);
          // Set chart options
          var options = {
            'title': 'How Much Pizza I Ate Last Night',
            'width': 400,
            'height': 300
          };
          // Instantiate and draw our chart, passing in some options.
          var chart = new google.visualization.PieChart(document.getElementById(divid));
          chart.draw(data, options);
          console.log(divid);
        } else {

note: the callback can be placed in the load statement

charts can be drawn anytime, once the callback has been called

this callback can be used instead of...

$(document).ready(function(){});

-- and / or --

window.addEventListener('load', function () {}, false);

Community
  • 1
  • 1
WhiteHat
  • 59,912
  • 7
  • 51
  • 133