0

I am using google visualization to draw charts from data that I am sending by JSON. I read the data with JQUERY, however, when I want to use it in the javascript I get the variable undefined problem. Here is my code:

google.load("jquery", "1.3.2");
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(function(){
    $.get("http://localhost:8081/petclinic/users/7/campaigns/2/queries/4/analyze", function(data){
        console.log(data);

        results.push(data[0][0]);
        results.push(data[0][1]);
        for (var i = 1; i < data.length; i++) {
                results.push(data[i][0]);
                results.push(parseInt(data[i][1]));
        }
        console.log(results);
    });
    var data = google.visualization.arrayToDataTable(results);

    var options = {
      title: 'Company Performance'
    };

    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, options);
});
mahsa.teimourikia
  • 1,664
  • 9
  • 32
  • 64

1 Answers1

1

You need to put your google map code inside ajax callback, because after ajax your data in line google.visualization.arrayToDataTable(data); is undefined because it's executed before the ajax callback.

google.setOnLoadCallback(function(){
    $.get("http://localhost:8081/petclinic/users/7/campaigns/2/queries/4/analyze", function(data){
        console.log(data);

        results.push(data[0][0]);
        results.push(data[0][1]);
        for (var i = 1; i < data.length; i++) {
                results.push(data[i][0]);
                results.push(parseInt(data[i][1]));
        }
        console.log(results);

        var data = google.visualization.arrayToDataTable(data); // data or result ?

        var options = {
          title: 'Company Performance'
        };

        var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
        chart.draw(data, options);
    });

});
jcubic
  • 61,973
  • 54
  • 229
  • 402
  • it didn't work. the thing is that in Jquery I could convert my data as it is written here. but in javascript I get something like this: ["[", undefined, "[", NaN, """, NaN, "t", NaN, "i", NaN, "m" – mahsa.teimourikia Jun 10 '13 at 10:28
  • 1
    @MahsaTeimourikia I jut notice that you forgot to treat the data as json, right now it's just string. use `getJSON` function instead – jcubic Jun 10 '13 at 10:44