views:

77

answers:

2

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!

+1  A: 

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.

Matthew Flaschen
A: 

The success callback from .getJSON() will fire, when the underlaying XmlHttpRequest readyState 4 is fired. Thus, the code that is outside from your success callback will execute before that ajax event happens.

Put your outside code into the success handler and you will be fine.

jAndy