Reputation: 3800
Newbie to Google Charts, I am trying to create a Google Chart, controller returns JSON data like
{"data":[["In Progress","10"],["Completed","20"],["Deleted","5"],["Overdue","8"]]}
But data required for Google chart should be like
[["In Progress",10],["Completed",20],["Deleted","5"],["Overdue",8]]
I have following JS function:
$(document).ready(function () {
$.ajax({
url: '@Url.Action("TaskStatus", "Graph")',
data: "",
dataType: "json",
type: "POST",
contentType: "application/json; chartset=utf-8",
success: function (data) {
var jsonData = JSON.stringify(data);
var dt = new google.visualization.DataTable();
dt.addColumn('string', 'Tasks');
dt.addColumn('number', 'Count');
$.each(arrJson, function (i, obj) {
$.each(obj, function (i, o) {
console.log(o[1]);
dt.addRow(o[0],parseInt(o[1])); // here I get error of datatype for "Count" column
})
})
chartData = dt;
},
error: function (err) {
alert(err);
console.log(err);
}
}).done(function () {
drawChart();
})
})
function drawChart()
{
var options = {
width: '500px',
title: "Task Status",
pointSize: 20,
chartArea:{width:"100%",height:"100px"}
};
var pieChart = new google.visualization.PieChart(document.getElementById('chart_div'));
pieChart.draw(chartData, options);
}
Controller returns
List<object> temp = new List<object>();
temp.Add(new[] { "In Progress", "10" });
temp.Add(new[] { "Completed", "20" });
temp.Add(new[] { "Deleted", "5" });
temp.Add(new[] { "Overdue", "8" });
return Json(new { data = temp });
Please advice how to fix this? Thanks a lot in advance!
Upvotes: 2
Views: 1423
Reputation: 1039588
You should not use the JSON.stringify
function in your AJAX success callback as this will transform the object you got from the server into a string. You can try this:
success: function (result) {
var dt = new google.visualization.DataTable();
dt.addColumn('string', 'Tasks');
dt.addColumn('number', 'Count');
// Taking the "data" property as your controller returns it that way
var data = result.data;
$.each(data, function (i, obj) {
var label = obj[0];
var value = parseInt(obj[1]);
dt.addRow([label, value]);
});
chartData = dt;
},
Upvotes: 2
Reputation: 192
dt.addRow accept only array or null which that error says
Refere : https://developers.google.com/chart/interactive/docs/reference#addrow
check below fiddle where i have updated you code.
check here
http://jsfiddle.net/79ffvayr/109/
Upvotes: 0