I have this JS file in asp.netcore. I'm trying to generate a pie chart from my database and there is only 1 row of data. I'm not getting any errors but only the title gets rendered but not pie chart. My JS code
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
url: '/Index?handler=GlobalChartData',
dataType: 'json',
contentType: 'application/json',
type: 'GET',
success: MyChart
});
function MyChart(globalData) {
var data = new google.visualization.DataTable(globalData);
data.addColumn('string', 'GlobalCases');
data.addColumn('number', 'Data');
data.addRows([
['NewConfirmed', globalData.NewConfirmed],
['NewDeaths', globalData.NewDeaths],
['NewRecovered', globalData.NewRecovered],
['TotalConfirmed', globalData.TotalConfirmed],
['TotalDeaths', globalData.TotalDeaths],
['TotalRecovered', globalData.TotalRecovered]
]);
var options = { 'title': 'Global Covid Data' };
var chart = new google.visualization.PieChart(document.getElementById('ChartForGlobal'));
chart.draw(data, options);
};
}
my c# code
public JsonResult OnGetGlobalChartData()
{
var globalData = _context.GlobalContexts.ToList();
return new JsonResult(globalData);
}
Edit: In add rows, globalData.NewConfirmed -> NewConfirmed is undefined and so are the others.
I changed my add rows to
for (var i = 0; i < globalData.length; i++)
{
data.addRows([
['NewConfirmed', Number(globalData[i].NewConfirmed)],
['NewDeaths', Number(globalData[i].NewDeaths)],
['NewRecovered', Number(globalData[i].NewRecovered)],
['TotalConfirmed', Number(globalData[i].TotalConfirmed)],
['TotalDeaths', Number(globalData[i].TotalDeaths)],
['TotalRecovered', Number(globalData[i].TotalRecovered)]
]);
}
Now my chart is generated. Thank you @Swati.