javascript - return array from ajax -
this question has answer here:
- how return response asynchronous call? 21 answers
i worked on chartjs , take json 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 = []; (var = 0; < mydata.length; i++) { chartjsdata.push(mydata[i].count); chartjslabel.push(mydata[i].date); }
and put in labels , data:
var barchartdata = { labels: chartjslabel, datasets: [{ fillcolor: "rgba(220,280,220,0.5)", strokecolor: "rgba(220,220,220,1)", data: chartjsdata }] };
looking good, doesn't work. json data like:
[{"date":"12.2014","count":"62"},{"date":"11.2014","count":"58"}]
and if replace ajax clear json in mydata
variable to:
var mydata = [{"date":"12.2014","count":"62"},{"date":"11.2014","count":"58"}];
it work perfectly. doing wrong?
you can not return
ajax
asynchronous
in nature, usecallback
function or initialization ofbarchartdata
in ajax success handler.
try this:
$.ajax({ method: "get", cache: false, url: "charts/applieschart.php", success: function(mydata) { var chartjslabel = []; var chartjsdata = []; (var = 0; < 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 }] }; } });
Comments
Post a Comment