Reputation: 5327
I am trying to draw Doughnut Chart using chartjs I am getting proper json response from my localhost my code is :
$(document).on('click', '#plotGraph', function(event) {
event.preventDefault();
alert("hello");
$.getJSON("PlotExpenseGraph", function(data1) {
alert("hiiiii");
console.log(data1);
console.log(data1.expenseList[0].param);
var pieData;
$.each(data1.expenseList, function(position, expenseList) {
console.log(expenseList.param);
console.log(expenseList.totalCount);
console.log(expenseList.totalValue);
pieData = {
value: expenseList.totalValue,
color: "#F7464A",
highlight: "#FF5A5E",
label: expenseList.param
}
});
var ctx = $("#myChart").get(0).getContext("2d");
var myNewChart = new Chart(ctx);
new Chart(ctx).Doughnut(pieData);
});
});
<script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.1/Chart.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<a href="#" id="plotGraph">Plot graph</a>
<canvas id="myChart" width="500" height="300"></canvas>
My console data is
param: "Advertising"
totalCount: 2
totalValue: 754
Advertising
Advertising
2
754
My code is not plotting any figure and also it is not giving any error on console. What scanges should I make to work above code properly.
Upvotes: 0
Views: 742
Reputation: 74076
ChartJS expects an array of objects as parameter to the Doughnut()
method. You on the other hand just create the objects and thereby overwrite the last object.
Instead you should declare pieData
to be an array and add entries inside the each()
callback like this:
$(document).on('click', '#plotGraph', function (event) {
event.preventDefault();
$.getJSON("PlotExpenseGraph", function (data1) {
// prepare parameter to ChartJS
var pieData = [];
$.each(data1.expenseList, function (position, expenseList) {
// add respective entry
pieData.push({
value : expenseList.totalValue,
color : "#F7464A",
highlight : "#FF5A5E",
label : expenseList.param
});
});
// paint
var ctx = $("#myChart").get(0).getContext("2d");
var myNewChart = new Chart(ctx);
new Chart(ctx).Doughnut(pieData);
});
});
Upvotes: 1