I try to get the dataUrl (something similar to what this page link does ) of a graph generated with Google Charts and save it in a variable, the graph is generated as follows:
var result;
google.charts.load("current", {packages:['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Ciudad', 'Poblacion'],
['Tulua', 12312 ],
['Bogota', 22222 ]
]);
var options = {
title: "Max Poblacion",
};
var chart_div = document.getElementById('chart_div');
var chart = new google.visualization.PieChart(chart_div);
google.visualization.events.addListener(chart, 'ready', function () {
chart_div.innerHTML = '<img src="' + chart.getImageURI() + '">';
console.log(chart.getImageURI());
result = chart.getImageURI();
});
chart.draw(data, options);
}
console.log(result);
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id='chart_div'></div>
I can show what I need but I can't save it in a variable, because when I try to do it it shows me that it is undefined.
Is it necessary to display the chart in a div to get its dataUrl chart.getImageURI()
?
The problem is that
you have a Career Condition: theconsole.log(result)
is executing before the variable with the dataUrl is filled.Place the
console.log(result)
on the line following aresult = chart.getImageURI();
and you will see that the variable is being saved. You can also try this:Now, I guess what you need to do is do something after the graph is generated, like send the image via ajax to the server, or show it in a new window, etc. for this, you must call the function that executes that operation from within the event
ready
of thechart
:Update
As @rnd indicates, it's not really a Race Condition, because by definition it refers to access to a shared resource from different processes/threads, and Javascript handles asynchronous calls (events, setTimeout...) in a single thread ( the event loop ): the event
ready
ofchart
will not fire, at least, until the function has finisheddrawChart
.