Sample code: Both of these seem to work ok, to display a message:
google.load("visualization", "1", { packages: ["corechart"] });
...
$(document).ready(function () {
google.setOnLoadCallback(function () {
alert('from inside ready 1');
});
});
$(document).ready(function () {
google.setOnLoadCallback(alert('from inside ready 2'));
});
Note: I'm using alert(..) just for debugging purposes - my real code draws charts. Now, I want to use these techniques inside $.ajax e.g. :
$.ajax({
type: "POST",
...
success: function (result) {
if (result.d) {
$(document).ready(function () {
alert('sucess');
// option 1
google.setOnLoadCallback(function () {
alert('from inside ready 3');
});
// option 2
// google.setOnLoadCallback(alert('from inside ready 4'));
});
Now, on ajax success, I can see "sucess" shown, but option 1 doesn't seem to work. i.e. I don't see "from inside ready 3". If I enable the code at option 2, and comment out the code for option 1, I DO see "from inside ready 4".
So it seems that option 2 works, but not option 1, from a jquery ajax call. Can anyone shed some light? Is option 2 100% safe to use? It seems to work, but all the examples I've seen seem to use option 1.
first, you're using the old version of google charts,
the
jsapi
library should no longer be used,see the release notes...
old:
<script src="https://www.google.com/jsapi"></script>
current:
<script src="https://www.gstatic.com/charts/loader.js"></script>
this will only change the load statement...
from...
to...
next, you don't need to use the callback every time you need to draw a chart,
it only needs to be used once, to ensure google charts has been loaded.
and there are several ways to use the callback,
you can use the updated
setOnLoadCallback
function.or you can place the callback directly in the
load
statement.or what I prefer, the promise it returns. (google includes a promise polyfill for IE)
now to the question at hand,
google's
load
statement will wait for the document to load by default,so you can use
google.charts.load
in place of$(document).ready
recommend loading google first, then using ajax to get data, then draw your charts.
something similar to the following setup...