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?
Related
I have a php, jquery, jqueryMobile, highcharts page with several charts on one page.
No i added an ajax call to load event to get live data into the charts. but i have to declare this in every Highcharts object, no matter which way i try it's not working as global function.
Here parts of the code i have and which is working
$(document).ready(function () {
// define sensorName
var sensorName = "rflinkstation";
chart1 = new Highcharts.chart({
"chart": {
"renderTo": sensorName,
"events": {
"load": function() {
var series = this.series[0];
setInterval(function() {
$.ajax({
url: 'sensorAjaxData.php',
success: function(point) {
console.log("ajax request for = " + sensorName);
// add the point
series.addPoint(point, true, true);
},
cache: false,
data: { "sensorName": sensorName,
"stationID": <?php echo $stationID;?>,
}
});
}, 60000);
}
}
},
"series": [{
...
$(document).ready(function () {
// define sensorName
var sensorName = "batteryvolt1";
chart2 = new Highcharts.chart({
"chart": {
"renderTo": sensorName,
"events": {
"load": function() {
var series = this.series[0];
setInterval(function() {
$.ajax({
url: 'sensorAjaxData.php',
success: function(point) {
console.log("ajax request for = " + sensorName);
// add the point
series.addPoint(point, true, true);
},
cache: false,
data: { "sensorName": sensorName,
"stationID": <?php echo $stationID;?>,
}
});
}, 60000);
}
}
},
"series": [{
....
What i try to achieve is to put the "load" function into a function to prevent copy pasting allot of code.
but if i declare something like
function getData(sensorName) {
and
events: { load: setInterval(getData(sensorName),6000) }
i loose the object and get this.series is undefined
My programming knoledge comes from pre object orinted programming and i do not fully understand the explanations in how to extend highcharts. Also the Highcharts live data example is written so that chart is a global variable and works only with one chart on a page.
so my question is how can i extend Highcharts with a load event that takes "sensorName" as argument and does an ajax call and insertrs the returned data into the right chart?
And a side question why is something like:
var series = this.series[0];
$.ajax({
...
series.addPoint(point)
...
working, and this not
$.ajax({
...
this.series[0].addPoint(point)
...
The this (Window object) inside of setInterval() function is not the same this (Chart object) as in chart.events.load() function. You can for example set the second parameter in getData() function which will indicate chart. Now getData() looks like this:
function getData(sensorName, chart) {
var series = chart.series[0];
$.ajax({
url: 'http://www.json-generator.com/api/json/get/bTNHrHVJmG?indent=2',
success: function(point) {
console.log('AJAX request for = ' + sensorName);
// add the point
series.addPoint(point, true, true);
},
data: {
sensorName: sensorName,
stationID: sensorName + 'ID' //<?php echo $stationID;?>,
},
cache: false
});
};
and it call in load event looks like this:
load: function() {
var chart = this;
setInterval(function() {
getData(chart.options.chart.renderTo, chart);
}, 5000);
}
Take a look at the example I prepared for you.
Example:
http://jsfiddle.net/a40qvy47/
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>");
I used below code to get request token and try to open twitter login page on button click in MVC5
But it will give sucess but in "data" field i am not able to get request token.
Please help me out how i can resolve my issue
var currentTime = new Date();
var time = currentTime.getTime();
var code = getNonce();
$.ajax({
type: "POST",
data: {
_url: "https://api.twitter.com/oauth/request_token"
},
dataType: "text",
headers: {
"oauth_nonce": code,
"oauth_callback": "http%3A%2F%2Fgoogle.com%2F",
"oauth_signature_method": "HMAC-SHA1",
"oauth_timestamp": time,
"oauth_consumer_key": "tCofU3Vil5BRFwQT7JdmpNKrP",
"oauth_signature": "oR9%2BzVEd4AlvpYdNwP6onuVDBFM%3D",
"oauth_version": "1.0"
},
success: function (data) {
debugger;
alert("Success!");
window.open('https://api.twitter.com/oauth/authorize?oauth_token=b6bb1a2f8ff545128f8c1c0aa216be8c')
console.log(data);
},
error: function(data) {
alert("Something went wrong...");
console.log(data);
}
});
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>
I was trying to implement dynamic google pie chart.But while doing so it is connecting to the database via json call but I cannot implement a piechat ,.hence i am not able to get the value for the pie chart.
My Json data which i want to is as follows:-
function getHealthReport()
{
var dataString = {auth_token: sessionStorage.auth_token,};
var mh_url = MH_HOST + '/reports/get_health_issues_report.json';
$.ajax(
{
type: "POST",
url: mh_url,
data: dataString,
dataType: "json",
success: function (data)
{/*
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart); <----- here i am getting piechart via hardcoding
function drawChart(){
var data = google.visualization.arrayToDataTable([
['Task','Hours per Day'],
['Work',11],
['Eat',2],
['Commute',2]
]);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('outer_tableDiv'));
chart.draw(data, options);}
*/
},
error: function (data)
{
alert("fail");
}
});
}
can anyone please help.