ROX February 2016

return array from ajax

i worked on Chartjs and take json from ajax:

 var myData = [];
 $.ajax({
     method: "GET",
     cache: false,
     url: "charts/applieschart.php",
     success: function (data) {
         myData = data;
     }
 });

next parse them on 2 different arrays:

  var chartjsLabel = [];
     var chartjsData = [];
     for (var i = 0; i < myData.length; i++) {
         chartjsData.push(myData[i].count);
         chartjsLabel.push(myData[i].date);
     }

and than i put it in labels and data:

 var barChartData = {
     labels: chartjsLabel,
     datasets: [{
         fillColor: "rgba(220,280,220,0.5)",
         strokeColor: "rgba(220,220,220,1)",
         data: chartjsData

     }]
 };

looking good, BUT it doesn't work. My json data look like:

[{"date":"12.2014","count":"62"},{"date":"11.2014","count":"58"}]

and if i replace ajax by clear json in myData variable to:

var myData = [{"date":"12.2014","count":"62"},{"date":"11.2014","count":"58"}];

it work perfectly. What i doing wrong?

Answers


Rayon Dabre February 2016

You can not return from ajax as it is asynchronous in nature, Use callback function or do the initialization of barChartData in ajax success handler.

Try this:

$.ajax({
  method: "GET",
  cache: false,
  url: "charts/applieschart.php",
  success: function(myData) {
    var chartjsLabel = [];
    var chartjsData = [];
    for (var i = 0; i < myData.length; i++) {
      chartjsData.push(myData[i].count);
      chartjsLabel.push(myData[i].date);
    }
    var barChartData = {
      labels: chartjsLabel,
      datasets: [{
        fillColor: "rgba(220,280,220,0.5)",
        strokeColor: "rgba(220,220,220,1)",
        data: chartjsData
      }]
    };
  }
});

Post Status

Asked in February 2016
Viewed 1,100 times
Voted 14
Answered 1 times

Search




Leave an answer