I am struggling to create a web page using Google charts. I attempted to build it with C# as a web form and retrieve data from a local database to JavaScript. However, I keep receiving an error stating that the data is undefined in the response from Ajax. This is the C# code snippet:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static object[] GetChartData()
{
List<GoogleChartData> data = new List<GoogleChartData>();
//MyDatabaseEntities is our dbContext
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
data = dc.GoogleChartDatas.ToList();
}
var chartData = new object[data.Count + 1];
chartData[0] = new object[]{
"Product Category",
"Revenue Amount"
};
int j = 0;
foreach (var i in data)
{
j++;
chartData[j] = new object[] { i.Product_Category, i.RevenueAmount };
}return chartData;
}
The JavaScript code looks like this:
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<!-- Javascript Job-->
<script src="Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
var chartData; // global variable to store chart data
google.load("visualization", "1", { packages: ["corechart"] });
// Fetching data for chartData
$(document).ready(function () {
$.ajax({
url: "GoogleChart.aspx/GetChartData",
data: "",
dataType: "json",
type: "post",
contentType: "application/json; charset=utf-8",
success: function (data) {
chartData = data.d;
alert(chartData);
},
error: function () {
alert("Error loading data! Please try again.");
}
}).done(function () {
// once data is loaded completely
google.setOnLoadCallback(drawChart);
drawChart();
});
});
function drawChart() {
var data = google.visualization.arrayToDataTable(chartData);
var options = {
title: "Company Revenue",
pointSize: 5
};
var pieChart = new google.visualization.PieChart(document.getElementById('chart_div'));
pieChart.draw(data, options);
}
</script>
<div id="chart" style="width: 500px; height: 400px">
</div>
Here is a picture of the database structure.
Can someone please guide me on how to fetch table data via Ajax and display it in a chart?