Sai Sai - 1 month ago 10
Ajax Question

How to use values from an ajax request in google charts?

I am creating an array of objects using Ajax to use as values in a google line chart, however the values do not render even though I can view them through the console.

I have tried using ajax complete function to call the charts once the values are set but it still doesn't work, I suspect it's due to scoping but I don't know how to resolve it. here is my code

complete array

studentCount[
{
month:1,
count:5
},
{
month:2,
count:3
},
{
month:3,
count:9
},
{
month:4,
count:0
}
{
month:5,
count:4
}
etc...
]


code

$.ajax({
dataType: "json",
url: url,
success: function (data) {
for (var i = 0; i < data.length; i++) {
studentCount[data[i].month -1].count = data[i].count;
}
}
});

$( document ).ajaxComplete(function() {
google.charts.load('current', {
packages: ['line']
});
google.charts.setOnLoadCallback(drawLineColors);

console.log(JSON.stringify(studentCount[0].count)) //returns correct value

function drawLineColors() {
var data = google.visualization.arrayToDataTable([
['Month', '2015'],
['January', studentCount[0].count],
['Febuary', studentCount[1].count],
['March', studentCount[2].count],
['April', studentCount[3].count],
['May', studentCount[4].count],
['June', studentCount[5].count],
['July', studentCount[6].count],
['August', studentCount[7].count],
['Septembre', studentCount[8].count],
['October', studentCount[9].count],
['November', studentCount[10].count],
['December', studentCount[11].count]
]);

var options = {
hAxis: {
title: 'Month'
},
vAxis: {
title: 'Number of Students'
},
colors: ['#4285f4', '#db4437']
};

var chart = new google.charts.Line(document.getElementById('chart_div'));
chart.draw(data, google.charts.Line.convertOptions(options));
}
});

Answer

recommend loading google first, you can include the callback directly in the load statement

once loaded, then call ajax

see following working snippet, adjust as needed to get proper data,
and change error to success as the url isn't reachable from here...

google.charts.load('current', {
  callback: function () {
    var url = 'some url';
    $.ajax({
      dataType: 'json',
      url: url,
      error: function (data) {  // <-- change 'error' to 'success' to run locally
        //for (var i = 0; i < data.length; i++) {
          //studentCount[data[i].month - 1].count = data[i].count;
        //}

        var studentCount = [
          { 
            month:1,
            count:5
          },
          { 
            month:2,
            count:3
          },
          { 
            month:3,
            count:9
          },
          { 
            month:4,
            count:0
          },
          { 
            month:5,
            count:4
          }
        ];

        var data = google.visualization.arrayToDataTable([
            ['Month', '2015'],
            ['January', studentCount[0].count],
            ['Febuary', studentCount[1].count],
            ['March', studentCount[2].count],
            ['April', studentCount[3].count],
            ['May', studentCount[4].count]
            // etc...
        ]);

        var options = {
            hAxis: {
                title: 'Month'
            },
            vAxis: {
                title: 'Number of Students'
            },
            colors: ['#4285f4', '#db4437']
        };

        var chart = new google.charts.Line(document.getElementById('chart_div'));
        chart.draw(data, google.charts.Line.convertOptions(options));

      }
    });
  },
  packages: ['line']
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

also, recommend using core chart instead of material,

several config options simply don't work with material charts

core chart, use package --> corechart
and chart --> google.visualization.LineChart

you can use config option theme: 'material' to get the core chart close to the look and feel of a material chart

see following working snippet...

google.charts.load('current', {
  callback: function () {
    var url = 'some url';
    $.ajax({
      dataType: 'json',
      url: url,
      error: function (data) {  // <-- change 'error' to 'success' to run locally
        //for (var i = 0; i < data.length; i++) {
          //studentCount[data[i].month - 1].count = data[i].count;
        //}

        var studentCount = [
          { 
            month:1,
            count:5
          },
          { 
            month:2,
            count:3
          },
          { 
            month:3,
            count:9
          },
          { 
            month:4,
            count:0
          },
          { 
            month:5,
            count:4
          }
        ];

        var data = google.visualization.arrayToDataTable([
            ['Month', '2015'],
            ['January', studentCount[0].count],
            ['Febuary', studentCount[1].count],
            ['March', studentCount[2].count],
            ['April', studentCount[3].count],
            ['May', studentCount[4].count]
            // etc...
        ]);

        var options = {
            hAxis: {
                title: 'Month'
            },
            vAxis: {
                title: 'Number of Students'
            },
            colors: ['#4285f4', '#db4437'],
            theme: 'material'
        };

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

      }
    });
  },
  packages: ['corechart']
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>