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!
getJSONis asynchronous. Do this instead:The issue is that
getJSONreturns immediately. Only later, when the request completes, is your callback called. In the meantime,chart.drawmay 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.