generate Google Chart using JSON - javascript

I am working on a web application which retrieves JSON data from servlet and uses it to generate chart. I am successful in retrieving the requisite json file in Google Chart compliant JSON format but am unable to generate the chart.
The jsbin of google chart is in the foll link: http://jsbin.com/hofaqidape/1/watch?html,js,output
The data var should be generated using JSON and I am doing the following stuff in my servlet
response.setContentType("application/json");
String json;
newClass s =new newClass();
List<newClass> classes = new ArrayList<newClass>();
s.setCount(1);
s.setName("Name");
classes.add(s);
s =new newClass();
s.setCount(2);
s.setName("Name1");
classes.add(s);
s =new newClass();
s.setCount(3);
s.setName("Name2");
classes.add(s);
s =new newClass();
s.setCount(1);
s.setName("Name4");
classes.add(s);
json="{ cols :[ { label : name , type : string },{ label : count , type : number }], rows :[";
String ss;int y;
for(newClass class1:classes)
{
ss=class1.getName();
y=class1.getCount();
json+="{ c : [{ v : "+ss+" },{ v : "+y+"}]},";
}
json=json.substring(0, json.length()-1);
json+="]}";
JSONObject js=null;
try {
js = new JSONObject(json);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
out.print(js);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
on the html side I have the foll code for my chart generation:
$(document).ready(function(){
$.ajax({
url : "Serv",
dataType: 'json',
contentType: 'application/json',
success : function(result) {
var dat=result;
alert(JSON.stringify(dat));
google.load('visualization', '1', {
packages: ['corechart', 'bar']
});
google.setOnLoadCallback(drawBasic);
function drawBasic() {
var data = new google.visualization.DataTable(dat);
var options = {
title: 'Motivation Level Throughout the Day',
hAxis: {
title: 'Name'
},
vAxis: {
title: 'Count'
}
};
var chart = new google.visualization.ColumnChart(
document.getElementById('chart_div'));
chart.draw(data, options);
}
},
complete: function()
{
alert('done');
}
});
});
alert(JSON.stringify(dat)) gives the alert as
{"cols":[{"label":"name","type":"string"},{"label":"count","type":"number"}],"rows":[{"c":[{"v":"Name"},{"v":1}]},{"c":[{"v":"Name1"},{"v":2}]},{"c":[{"v":"Name2"},{"v":3}]},{"c":[{"v":"Name4"},{"v":1}]}]}
which is a valid JSON.
how do I generate the chart using this data just like I did in jsbin?

google.setOnLoadCallback() set up a callback function to execute when Google Visualization API loaded, so google.load needs to load from the front explicitly. I am recalling it when i worked on them lately. My recommendation would be to move google.load and drawBasic() outside from AJAX call and use them in success of call, like this...
$(document).ready(function(){
google.load('visualization', '1', {
packages: ['corechart']
});
function drawBasic(d) {
var data = new google.visualization.DataTable(d);
var options = {
title: 'Motivation Level Throughout the Day',
hAxis: {
title: 'Name'
},
vAxis: {
title: 'Count'
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
$.ajax({
url : "Serv",
dataType: 'json',
contentType: 'application/json',
success : function(result) {
google.setOnLoadCallback(drawBasic(JSON.stringify(result)));
},
complete: function(){
// whatever..
}
});
});
Update: You only need to specify packages: ['corechart'] which will define most basic charts, including the pie, bar, and column charts.

finally got the answer to this question.
removed google.setOnLoadCallback() and called drawBasic() function from ajax call itself. somehow setOnLoadCallback() and $(document).ready() doesnt seem to coexist.
working code:
<script>
google.load('visualization', '1', {
packages: ['corechart']
});
function drawBasic(d) {
var data = new google.visualization.DataTable(d);
var options = {
title: 'Sample Data',
hAxis: {
title: 'Name'
},
vAxis: {
title: 'Count'
},
width: 600,
height: 240
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
$(function(){
$("#dd").change(function(){
if($(this).val()!='null')
{
$.ajax({
url : "Serv",
data: {dd1:$(this).val()},
dataType: 'json',
contentType: 'application/json',
success : function(result) {
drawBasic(result);
},
complete: function(){
// whatever..
}
}) ;
}
else
{
$("#chart_div").empty();
alert('please select');
}
});
});
</script>

Related

Pie chart crashes when no data from JSON

I am a beginner and learning web development. In my sample project I have created Pie Chart using ChartJS. I am getting data from REST Service. Everything is working fine and pie chart is getting rendered properly. The problem is when there is null data from REST then I am getting error in Chart.js.
Error:
JSON DATA FROM REST:
My sample project uses BackboneJS. I know the error is because there is no data coming from REST. How can I handle that so that m Pie Chart does not crash.
Below is the MODEL:
define(['backbone'], function(Backbone) {
var chart = Backbone.Model.extend({
urlRoot: 'SAMPLE REST URL',
defaults: function() {
return {
currMonthOccAvailVac: [],
};
},
fetch: function(data) {
var d = $.Deferred();
var self = this;
var ajaxRequest = $.ajax({
url: this.urlRoot,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(data)
});
ajaxRequest.done(function(json) {
var graphVar = {
currMonthOccAvailVac: [],
}
var yearSelected = (localStorage.getItem('date')).split("-")[0];
var monthSelected = (localStorage.getItem('date')).split("-")[1];
for (var i = 0; i < json.length; i++) {
var monthYear = json[i].columnstrDate.split("/");
var year = monthYear[0];
var month = monthYear[1];
if(month.length == 1)
if(month == (monthSelected - 1) && year == yearSelected)
{
graphVar.currMonthOccAvailVac.push(json[i].columndecOccPercentage);
graphVar.currMonthOccAvailVac.push(json[i].columndecVacantUnitsPercentage);
graphVar.currMonthOccAvailVac.push(json[i].columndecUnavailableUnitsPercentage);
}
}
self.set({
currMonthOccAvailVac: graphVar.currMonthOccAvailVac,
});
d.resolve();
});
//failure callback for ajax request.
ajaxRequest.fail(function(jqXHR, status) {
// Handle fail request
d.reject();
});
return d.promise();
}
});
// returning the model
return {
chart: chart
};
});
Place in ChartJS where actually code is breaking:
So how can I make sure even if graphvar.currMonthOccAvailVac has no value the pie chart does not crash. Kindly guide me.
EDIT
Currently in my View Model I did something like below. But I am not sure if this the right way to handle.
define(['backbone'], function(Backbone) {
var sixthSubViewModel = Backbone.View.extend({
template: _.template($('#myChart6-template').html()),
render: function() {
$(this.el).html(this.template());
var ctx = this.$el.find('#pieChart')[0];
var data = {
datasets: [{
data: this.model.attributes.currMonthOccAvailVac,
label: 'My dataset' // for legend
}],
labels: [
"Rented",
"Vacant",
"Unavailable",
]
};
// I AM CHECKING HERE THE LENGTH AND THE RNEDERING THE PIE CHART
if (this.model.attributes.currMonthOccAvailVac.length > 1)
var pieChart = new Chart(ctx, {
type: 'pie',
data: data,
otpions: {
legend: false
}
});
WHAT SHALL I PUT IN THE ELSE PART
},
initialize: function() {
this.render();
}
});
return sixthSubViewModel;
});

Uncaught Error: not an array ASP.NET

I am trying to fetch data from SQL server via JSON format into Google charts but I am getting the following error
Uncaught error: not an array - Resolved. Answer below in EDIT
Uncaught TypeError: Cannot read property 'load' of undefined
I am following this tutorial
JS Code in charts.aspx
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script>
var chartData; // globar variable for hold chart data
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
// Here We will fill chartData
$(document).ready(function () {
$.ajax({
url: "charts.aspx/GetChartData",
data: "",
dataType: "json",
type: "POST",
contentType: "application/json; chartset=utf-8",
success: function (data) {
chartData = data.d;
},
error: function () {
alert("Error loading data! Please try again.");
}
}).done(function () {
// after complete loading data
drawChart();
});
});
function drawChart() {
var data = google.visualization.arrayToDataTable(chartData);
var options = {
title: "Count",
pointSize: 5
};
var barChart = new google.visualization.BarChart(document.getElementById('chart_div'));
barChart.draw(data, options);
}
</script>
<script type="text/javascript">
google.charts.load('current', {packages: ['corechart']});
google.charts.setOnLoadCallback(drawChart);
HTML Code in charts.aspx
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<div id="chart_div" style="width:500px;height:400px">
<%-- Here Chart Will Load --%>
</div>
</asp:Content>
C# Code - charts.aspx.cs
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static object[] GetChartData()
{
List<Main> data = new List<Main>();
//Here MyDatabaseEntities is our dbContext
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
data = dc.Mains.ToList();
}
var chartData = new object[data.Count + 1];
chartData[0] = new object[]{
"Status",
"status reason"
};
int j = 0;
foreach (var i in data)
{
j++;
chartData[j] = new object[]
{
i.Incident_Status.ToString(), i.Status_Reason.ToString()
};
//chartData[j] = new object[] { i.Year.ToString(), i.Electronics, i.BookAndMedia, i.HomeAndKitchen };
}
return chartData;
}
JSON Output
{Message: "Authentication failed.", StackTrace: null,…}
ExceptionType: "System.InvalidOperationException"
Message : "Authentication failed."
StackTrace : null
EDIT -
I tried adding
<authorization>
<allow users="*" />
</authorization>
in web.config because I was facing authorization error. But it still didn't help.
EDIT2 -
I added in App_Date/RouteConfig.js
settings.AutoRedirectMode = RedirectMode.Off;
This resolved the JSON issue. I am now getting proper response
d: [["Status", "status reason"], ["Closed", "No Further Action Required"],…]}
d: [["Status", "status reason"], ["Closed", "No Further Action Required"],…]
Still data is not loading.
You need to parse JSON before passing parameter to function:
function drawChart() {
var data = google.visualization.arrayToDataTable(JSON.parse(chartData));
var options = {
title: "Count",
pointSize: 5
};
var barChart = new google.visualization.BarChart(document.getElementById('chart_div'));
barChart.draw(data, options);
}
UPDATE:
It doesn't matter I just did mistake $.parseJSON is deprecated. So I changed a bit. But I just changed your javascript function.
UPDATE 2:
In your JSCode: var data = google.visualization.arrayToDataTable(chartData);
Fix: var data = google.visualization.arrayToDataTable(JSON.parse(chartData));

try catch on static function asp.net

i try show error message
i have a link button in grid view ..i call highcharts when i click on this link button and also this static function.. through this static function i get data and then call this function through javascript so when i click on this button chart is display but when there is no chart it shows error in code so for this i want to show alert box when there is no chart..
public static function(int ID)
try
{
}
catch (Exception ex)
{
Response.Write("<script>alert('" + Server.HtmlEncode(ex.ToString()) + "')</script>");
}
i try above but this shows error message
Error 3 An object reference is required for the non-static field,
method, or property 'System.Web.UI.Page.Server.get'
Error 2 An object
reference is required for the non-static field, method, or property
'System.Web.UI.Page.Response.get'
lbViewChart is link button ...
jquery
<script type="text/javascript">
var strArray = "[['sfdsdfLi', 9],['Kiwsdfi', 3],['Mixesdfd nuts', 1],['Oranges', 6],['Grapes (bunch)', 1]]";
$(function () {
$('[ID*=lbViewChart]').on('click', function () {
var row = $(this).closest('tr');
var Id = row.find('td')[0].firstChild.data;
var obj = {};
obj.ID = Id;
GetData(obj);
return false;
});
});
function GetData(obj) {
$.ajax({
type: "POST",
url: "WebForm1.aspx/GetVoiliations",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (result) {
alert(result.d);
alert('u');
//start
strArray = result.d;
var myarray = eval(strArray);
$('#container').highcharts({
chart: {
type: 'pie',
options3d: {
enabled: true,
alpha: 45
}
},
title: {
text: 'Contents of Highsoft\'s weekly fruit delivery'
},
subtitle: {
text: '3D donut in Highcharts'
},
plotOptions: {
pie: {
innerSize: 100,
depth: 45
}
},
series: [{
name: 'Delivered amount',
data: myarray
}]
});
//end
},
error: function (error) {
alert(error);
}
});
}
// });
</script>
any solution?
You cannot access Server directly in a static method instead for that use System.Web.HttpContext.Current.Server So the code will be like:
System.Web.HttpContext.Current.Response.Write("<script>alert('" + System.Web.HttpContext.Current.Server.HtmlEncode(ex.ToString()) + "')</script>");
Or include using System.Web; to the using section and then use HttpContext.Current.Server
Updates: -
The HttpContext.Current is a static property so you can access it Directly inside a static method. and hence you can access .Server and .Response` from this as like the following:
System.Web.HttpContext currentContext = System.Web.HttpContext.Current;
currentContext.Response.Write("<script>alert('" + currentContext.Server.HtmlEncode(ex.ToString()) + "')</script>");

Issue Deploying Google Charts

I am in the process of deploying a set of Google Charts into SharePoint 2013. I am running into this issue where it isn't loading my data. I have tested it out in just a standard application page and it works perfectly. I will show my code below:
<script type="text/javascript">
//approver chart
var chartDataApprover; // globarlvariable to hold chart data
google.load("visualization", "1", { packages: ["corechart"] });
$(document).ready(function () {
$.ajax({
url: "Chart_Application_Page.aspx/GetChartDataApprover",
data: "",
dataType: "json",
type: "POST",
contentType: "application/json; chartset=utf-8",
success: function (data) {
chartDataApprover = data.d;
},
error: function () {
alert("Error loading data! Please try again.");
}
}).done(function () {
//after data is loaded
google.setOnLoadCallback(drawChartApprover);
drawChartApprover();
});
});
</script>
//approver function
function drawChartApprover() {
var data = google.visualization.arrayToDataTable(chartDataApprover);
//groups chart data by name
var resultApprover = google.visualization.data.group(data, [0], [{ 'column': 1, 'aggregation': google.visualization.data.sum, 'type': 'number' }]);
var options = {
title: "Approver Spending",
pointSize: 5
};
var pieChartApprover = new google.visualization.PieChart(document.getElementById('chart_div_approver'));
pieChartApprover.draw(resultApprover, options);
}
I believe my error is coming on the line where I am setting the content type. I am deploying this into SharePoint 2013 via an Application Page... with code behind in C#.
Can anyone help me out with this issue?

how to use google chart using dynamic data from json

iam using mvc, i want to connect my data to google pie chart. so i used json to get list of names and their count using the following code
public JsonResult list()
{
var result= list.GroupBy(i => i.Name).Select(i => new { word = i.Key, count = i.Count()
return Json(result.ToList(), JsonRequestBehavior.AllowGet);
}
Using the google chart API
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "list",
dataType: "json",
async: false
}).responseText;
var data = google.visualization.DataTable(jsonData);
var options = {
title: 'Certificate details',
is3D: true,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
chart.draw(data, options);
}
i want to know how to get list of key value pairs of my data into pie chart.
i have googled for long time, everybody is giving code example with php.
Thankyou.
You can parse that data client-side like this:
function drawChart () {
$.ajax({
url: "list",
dataType: "json",
success: function (jsonData) {
var data = new google.visualization.DataTable();
// assumes "word" is a string and "count" is a number
data.addColumn('string', 'word');
data.addColumn('number', 'count');
for (var i = 0; i < jsonData.length; i++) {
data.addRow([jsonData[i].word, jsonData[i].count]);
}
var options = {
title: 'Certificate details',
is3D: true
};
var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
chart.draw(data, options);
}
});
}
I created a basic handler to provide some methods to work with dinamic google charts.
First you register the data or part of it. After this, you are able to render when necessary.
Look at: http://github.com/ahlechandre/chart-handler

Categories

Resources