Reputation: 117
I am working on creating dynamic values for a pie chart which is a graph from chart.js I have created a variable which contains multiple object values which needs to be passed in the array for pie graph. If I pass the variable nothing shows up but if I pass the same static values to the variable the pie chart starts working. I searched for various methods but could not make it work with my code. My code looks like this:
/*PIE Chart*/
var elements = [];
var counter;
jQuery.ajax({
type: 'POST',
url: 'ajax-request.php',
data: {},
success: function(response){
//here data is means the out put from the php file it is not
$('#StudentID').val()
var jsonData = JSON.parse(response);
console.log(elements);
var pieData;
for (var i = 0; i < jsonData.length; i++) {
counter = jsonData[i];
var sale = roundFloat(counter.sales,2);
elements+= '{value:'+sale+',color: "#FDB45C",highlight: "#FFC870",label:"'+counter.sku+'"},';
}
var pieData = [elements];
var ctx = document.getElementById("pie-chartjs").getContext("2d");
window.myPie = new Chart(ctx).Pie(pieData);
}
});
Upvotes: 0
Views: 2126
Reputation: 41065
You need to make a couple of changes to your code to make this work.
pieData
should be an array of objects. So instead of appending a string, you need to push the object into the array. Once you do that that elements
is an array of objects and you can directly assign it to pieData
Below is the changed code block
for (var i = 0; i < jsonData.length; i++) {
counter = jsonData[i];
var sale = roundFloat(counter.sales, 2);
elements.push({
value: sale,
color: "#FDB45C",
highlight: "#FFC870",
label: counter.sku
})
}
var pieData = elements;
Upvotes: 1