I want to build a web page with google charts. I tried to build it with c# as a web form and get data from local database to javascript. But that's not working and i'm having data is undefined in the response of ajax. This is the code of c#
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static object[] GetChartData()
{
List<GoogleChartData> data = new List<GoogleChartData>();
//Here 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;
}
and the javascript code is:
<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; // globar variable for hold chart data
google.load("visualization", "1", { packages: ["corechart"] });
// Here We will fill 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 () {
// after complete loading data
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>
PLEASE HELP!! how to get my table data in ajax and put them in chart?
first, recommend not using
jsapi
to load the library, according to release notes...<script src="https://www.gstatic.com/charts/loader.js"></script>
this will only change the
load
statement...as seen above, the
callback
can be set in theload
statementthe
callback
will let you know when google charts has loaded, along with the domthus no need for
setOnLoadCallback
or$(document).ready
as for the rest, recommend the following setup...