2

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?

Andreas
  • 21,535
  • 7
  • 47
  • 56
ROX
  • 39
  • 4
  • Check the execution order of your methods. It is possible that the myData is not populated yet when those that relate on it are executed - thus no go. Check the Promises usage of ajax method in jQuery and chain your methods or check the Rayon Dabre callback solution. – mzografski Feb 08 '16 at 11:01

1 Answers1

0

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
      }]
    };
  }
});
Rayon
  • 36,219
  • 4
  • 49
  • 76