0

I'm attempting to change the value of a global variable inside a javascript function, however, the value does not seem to be taken, and I'm not sure why. (Admittedly, I am not an experienced javascript person.) Here is my code:

var title_chart = "";

google.load("visualization", "1", {packages:["corechart"]});

google.setOnLoadCallback(drawChart);

function drawChart() {
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Country');
  data.addColumn('number', 'Number of Entries');

  jQuery.getJSON('/data/stats.json', function(chart_data) {
    title_chart = chart_data.chart_title;
    jQuery.each(chart_data.stats, function(index, value){
      data.addRows(1);
      data.setValue(index, 0, value.chart_label);
    });
  });

  var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
  chart.draw(data, {width: 450, height: 300, title: title_chart});

}

Thanks!

2
  • 1
    Which global variable? Can you be more specific? Commented Jul 22, 2010 at 5:38
  • You need to use window.variable="value you want to set" to set the value of global javascript variable see the link for you reference javatpoint.com/oprweb/test.jsp?filename=jsglobalvariable2 Commented Jun 1, 2017 at 5:45

1 Answer 1

1

getJSON is asynchronous. Do this instead:

jQuery.getJSON('/data/stats.json', function(chart_data) {
  var title_chart = chart_data.chart_title;
  jQuery.each(chart_data.stats, function(index, value){
    data.addRows(1);
    data.setValue(index, 0, value.chart_label);
  });

  var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
  chart.draw(data, {width: 450, height: 300, title: title_chart});
});

The issue is that getJSON returns immediately. Only later, when the request completes, is your callback called. In the meantime, chart.draw may have already run. By moving this code into the callback function, we ensure it runs at the right time. Also note that we can eliminate the global.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.