extending highcharts with an ajax load event - javascript

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/

Related

Redrawing the highchart column type graph on ajax success function

Actually i want to redraw the HighChart Bargraph on Ajax Success Function in which the parameter is send need help.
Below are my code
On Page Load Code (It Runs Perfect)
<script>
var chart = $(function () {
$('#chart').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Overdue Projects'
},
xAxis: {
categories: <?php print_r(isset($project) ? $project : []); ?>
},
yAxis: {
title: {
text: 'Hours'
}
},
series: <?php print_r($series); ?>
}, function (chart) { // on complete
if (chart.series.length < 1) { // check series is empty
console.log('Data Empty');
chart.renderer.text('No Data Available', 380, 120)
.css({
color: '#4572A7',
fontSize: '16px'
})
.add();
}
});
});
</script>
On Ajax Success Function Code (Unable to Update the series and categories)
<script>
$("select[name=GraphPro]").on('change', function () {
var proId = $(this).val();
$.ajax({
data: 'proId=' + proId,
type: "post",
url: "<?php echo base_url('admin_dashboard/drawBarChart'); ?>",
dataType: "json",
success: function (xyz)
{
var project = xyz.project;
chart.series = xyz.series;
var chart1 = new Highcharts.Chart(chart);
}
})
})
</script>
Really hard to say for sure without seeing the data in your variables what you are aiming for with the project variable.
That said, to update the chart (read: change) you can do the following assuming chart is the variable of your already existing chart;
Updated as per your comment:
<script>
$("select[name=GraphPro]").on('change', function () {
var proId = $(this).val();
$.ajax({
data: 'proId=' + proId,
type: "post",
url: "<?php echo base_url('admin_dashboard/drawBarChart'); ?>",
dataType: "json",
success:function(xyz) {
console.log(xyz.project); //Value is ["Chat"]
console.log(xyz.series); // Value is [{"name":"Estimated Hours","data":[3]},{"name":"Consumed Hours","data":[12]}]
chart.update({
xAxis:{ categories: xyz.project //print as xyz.project instead of above project value
},
series: xyz.series // print as xyz.series instead of above series value
});
}
})
})
</script>
Highchart API on update: http://api.highcharts.com/class-reference/Highcharts.Chart#update
Working example using update when button is clicked: http://jsfiddle.net/ewolden/crhh39v6/
To add additional series to your chart you need to use addSeries, like this:
<script>
$("select[name=GraphPro]").on('change', function () {
var proId = $(this).val();
$.ajax({
data: 'proId=' + proId,
type: "post",
url: "<?php echo base_url('admin_dashboard/drawBarChart'); ?>",
dataType: "json",
success: function (xyz)
{
var project = xyz.project; //don't know what the plan with this variable is
chart.addSeries(xyz.series);
}
})
})
</script>
Highchart API on addChart: http://api.highcharts.com/class-reference/Highcharts.Chart#addSeries

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;
});

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>");

JStree Async Search

Whe are busy building a web based app. And we inherited the code where the previous developers used jstree so now the whole site consist out of a tree that uses jstree.
Everything worked even the search on the tree, but then we came across a problem where certain tabs loaded too long because of the tree which was too big.
So we went and made the the tree async / lazy loading which works perfectly but know the problem is that the search doesn't work that well.
Because we made a api for the search which works but it doesn't do the call back after new tree has been loaded.
Can someone help because I've been struggling for 3 days now and its giving me a head ache.
// Tree Search
searchAjaxFunction: function () {
var TreeCustomApiRequest = {
nTreeCustomDesc: document.getElementById("tree_search").value,
nUserId: document.getElementById("TrendUserID").value,
nAccessLevel: document.getElementById("hfTrendAccessLevel").value
}
$.ajax({
type: "POST",
data: JSON.stringify(TreeCustomApiRequest),
url: 'api/TreeCustomSearch.aspx',
success: function (jsonData)
{
Tree.dataJson = jsonData;
// Clear the tree.
//Tree.dataJson = jsonData;
if ($("#tree").jstree()) {
$('#tree').jstree(true).settings.core.data = jsonData;
$('#tree').jstree(true).deselect_node(this);
$('#tree').jstree(true).toggle_node(this);
$('#tree').jstree(true).refresh();
}
},
contentType: "application/json"
});
},
onClickFunctionNode: function(node) {
Tree.treeDivIdSelector.jstree(true).toggle_node(node);
},
pluginsArray: ["search", "checkbox", "types", "json_data","html_data"],
treeMenuContextItems: {},
Init: function(initData) {
Tree.dataJson = initData.dataJson;
Tree.treeDivIdSelector = initData.chartDivId;
Tree.searchDivIdSelector = initData.searchDivId;
var apiUriTree = 'api/TreeCustomChildren.aspx';
Tree.treeDivIdSelector.jstree({
"checkbox": {
"keep_selected_style": true,
"three_state": false
},
"plugins": Tree.pluginsArray,
'core': {
'data': function (node, cb) {
// Fetch tree custom parent nodes
if (node.id === "#") {
cb(Tree.dataJson);
}
else {
var _cb = cb;
//Fetch tree custom Child nodes
var TreeCustomApiRequest = {
nUserId: document.getElementById("TrendUserID").value,
nAccessLevel: document.getElementById("hfTrendAccessLevel").value,
nTreeCustomParentId: node.id
}
function recieveData(data) {
cb(data);
}
$.ajax({
type: "POST",
data: JSON.stringify(TreeCustomApiRequest),
url: apiUriTree,
success: recieveData,
contentType: "application/json"
});
}
},
"themes": {
"icons": false
}
},
"contextmenu": {
items: Tree.pluginsArray.indexOf("contextmenu") > -1 ? Tree.treeMenuContextItems : null
}
});
var tree = Tree.treeDivIdSelector.jstree();
function getNode(sNodeID) {
return tree.get_node(sNodeID);
}
Tree.treeDivIdSelector.on('click', '.jstree-anchor', function(e) {
Tree.onClickFunctionNode(this);
}
);
//Tree.searchDivIdSelector.keyup(Tree.searchFunction);
},
The next code is in the client side......
<script type="text/javascript">
$(document).ready(function () {
var dataJson = <%=sTreeViewJson%>
Tree.Init({ dataJson: dataJson, chartDivId: $("#tree") });
$("#btnSearch").click(function () {
// Do the Ajax search
Tree.searchAjaxFunction();
//var value = document.getElementById("tree_search").value;
//Tree.searchFunction();
})
});
</script>
Thank you Nikolay, it was a stupid mistake from me so what I added was just this to my code:
success: function (jsonData, callback )
{
//Goes back to the Callback with the new search data
Tree.Init({ dataJson: jsonData, chartDivId: $("#tree"), searchDivId: $("#tree_search") });
$('#tree').jstree(true).refresh();
}
So I removed the
$('#tree').jstree(true).settings.core.data = jsonData;
$('#tree').jstree(true).deselect_node(this);
$('#tree').jstree(true).toggle_node(this);
Know it gets my data and refreshes the table with the init function while it has my new data.
Hope this also may help someone = ).

Load data to highchart using ajax

I'm loading a highchart graph using following function.
function reloadSubGraph(data){
$(function () {
$('#SubPatternContainer').highcharts({
plotOptions: {
events: {
update: function (event) {
}
}
},
title: {
text: 'Selected Pattern'
},
series:[{data:[[1,200],[2,200],[3,200]]}]
});
});
}
It works fine, but when using ajax call to load data as follows for same data string [{data:[[1,200],[2,200],[3,200]]}] as follows it doesn't show on graph.
function getSubPatternData(patternId,patternName){
$.ajax({
url: "/arcane/patternData1?patternId="+patternId+"&patternName="+patternName,
type: "get",
cache: false,
success: function(data) {
var tempdata=String(data);
reloadSubGraph(tempdata);
},
error:function(xhr, status, error){
alert(xhr.responseText);
}
});
}
Can anyone point me where i'm doing wrong here. when I see the returned results of ajax using alert(data) it shows the same string that i used in reloadSubGraph() function ([{data:[[1,200],[2,200],[3,200]]}])
when using with ajax i changed reloadSubGraph() funcion as follows.
function reloadSubGraph(data){
alert(data);
$(function () {<!--from w w w .j ava 2 s . c o m-->
$('#SubPatternContainer').highcharts({
plotOptions: {
events: {
update: function (event) {
}
}
},
title: {
text: 'Selected Pattern'
},
series:data
});
});
}

Categories

Resources