Highchart graph retrieve data from json url - json

I try to create a high chart graph from a url("http://avare.pe.hu/veri2.json") containing json data. But althrough the datas are retrieved (I tested it as writing it to console) The graph is not displayed. May you please help me?
My datas are
[{"names":["ADANA","ADIYAMAN","AFYONKARAHİSAR","ANKARA","BALIKESİR","BİLECİK","BURSA","ÇANAKKALE","EDİRNE","İSTANBUL","KIRKLARELİ","KOCAELİ","SAKARYA","TEKİRDAĞ","YALOVA"],"count":[3,1,1,4,162,5,532,79,33,714,50,435,66,81,2]}]
..................
The web page
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Pasta HighChart Grafiği</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var jsonurl = "http://avare.pe.hu/veri2.json";
var chart;
$.getJSON(jsonurl, function (json) {
var options = {
chart: {
renderTo: 'container',
type: 'pie',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: ''
},
subtitle: {
text: ''
},
xAxis: {
categories:[],
//type: 'category',
labels: {
rotation: -45,
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif'
}
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer', size: 160,
dataLabels: {
enabled: false
},
showInLegend: true,
dataLabels: {
enabled: true, connectorWidth: 2, connectorPadding: 1,
format: '<span style="font-size:14px; font-weight:bold">{point.percentage:.1f} %</span>',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
tooltip: {
pointFormat: 'Miktar, <b>{point.y:.1f} kton</b>'
},
series: [{
type:'pie',
data: []
}]
}
// options.series[0] = {};
// options.series[0].name = json[0]['names'];
// options.series[0].data = json[0]['count'];
var names = json[0]['names'];
var count = json[0]['count'];
var arr=new Array(names.length);
console.log(names[0]);
for (i = 0 ; i < name.length; i++) {
arr[i] = [names[i],count[i]];
}
options.series.data = arr;
chart = new Highcharts.Chart(options);
});
});
</script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script type="text/javascript" src="canvasjs.min.js"></script>
</head>
<body>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>

I have made an example with fixed data, and found one mistake in your code.
You wanted to add data to your series, but you forgot that your series object is an array, so you should add it with this code:
options.series[0].data = arr;
Here you can find an example how your chart will work with this correction: http://jsfiddle.net/worg6jLz/30/

Related

Google charts - data from local json file - custom tooltips

I'm using google charts to create dvb-c channels availability charts. The data for charts is red from local json file. The charts are working really fine, but I would like to add one feature to it, but I need some assistanse with it.
The feature I would like to add is custom tooltips, but I have no idea how to do it. I know I have to add the wanted data to json, but like I said Im not sure how to do it and how do I have to change my html code to make it work. I want tooltip to read local html file and show the content on tooltip.
Here is my html code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<div id="chart" style="width:3000px; height:600px;"></div>
</body>
<script>
// Visualization API with the 'corechart' package.
google.charts.load('visualization', { packages: ['corechart'] });
google.charts.setOnLoadCallback(drawLineChart);
function drawLineChart() {
$.ajax({
url: "./avail.json",
dataType: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data) {
var channels = [['Channel', 'HKI (%)', 'LTI (%)']]; // Define an array and assign columns for the chart.
// Loop through each data and populate the array.
$.each(data, function (index, value) {
channels.push([value.Channel, value.HKI, value.LTI]);
});
// Set chart Options.
var options = {
title: 'DVB-C Availability (HKI & LTI)',
series: {
0: { color: '#ff3385', lineWidth: 5, pointSize: 5 },
1: { color: '#000000', lineWidth: 1, pointSize: 3},
},
vAxis: { "title": "Availability (%)", maxValue: 100 },
hAxis : { "title": "Channels", showTextEvery:1, textStyle : {fontSize: 8, bold:'true' }, slantedText:true, slantedTextAngle:45 },
chartArea:{left:70,top:50,right:40,width:"90%",height:"70%"},
tooltip: {isHtml: true, trigger: 'both'},
legend: { position: 'top', textStyle: { color: '#555', fontSize: 14} }
};
// Create DataTable and add the array to it.
var figures = google.visualization.arrayToDataTable(channels)
// Define the chart type (LineChart) and the container (a DIV in our case).
var chart = new google.visualization.LineChart(document.getElementById('chart'));
chart.draw(figures, options); // Draw the chart with Options.
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Got an Error');
}
});
}
</script>
</html>
Here is little snippet of my current json file:
[
{ "Channel": "MTV Rocks", "HKI": 99.104700, "LTI": 98.760400 },
{ "Channel": "MTV3 HD", "HKI": 99.724600, "LTI": 99.724600 },
{ "Channel": "MTV3", "HKI": 100.000000, "LTI": 100.000000 },
]
Should I add something like this to json ?
[
{ "Channel": "MTV Rocks", "HKI": 99.104700, <object data="./hki1.html"></object> "LTI": 98.760400, <object data="./lti1.html"></object> },
{ "Channel": "MTV3 HD", "HKI": 99.724600, <object data="./hki1.html"></object>"LTI": 99.724600, <object data="./lti1.html"></object> },
{ "Channel": "MTV3", "HKI": 100.000000, object data="./hki1.html"></object>"LTI": 100.000000, object data="./lti1.html"></object> },
]
If this is the right way to change json, I have no idea how to change the html code to make this work.
Maybe someone can help me out with this ?
first, 'visualization' is not a valid version number for google charts.
it looks the this was left over from the old library loader code.
use 'current' instead...
google.charts.load('current', { packages: ['corechart'] });
next, you'll need to copy the html from the file into the json,
rather than trying to reference an external file.
the tooltip is only expecting an html snippet, not a full blown file.
to add the custom tooltip, first we need to add the column for the tooltip.
it should be an object, as follows...
{type: 'string', role: 'tooltip', p: {html: true}}
if you want a tooltip for both "HKI" & "LTI",
you need to add the above tooltip column after each column heading...
var channels = [['Channel', 'HKI (%)', {type: 'string', role: 'tooltip', p: {html: true}}, 'LTI (%)', {type: 'string', role: 'tooltip', p: {html: true}}]];
include the html when loading the rows...
$.each(data, function (index, value) {
channels.push([
value.Channel,
value.HKI,
'<div>custom html goes here</div>',
value.LTI,
'<div>custom html goes here</div>'
]);
});
see following working snippet for an example...
google.charts.load('current', { packages: ['corechart'] });
google.charts.setOnLoadCallback(drawLineChart);
function drawLineChart() {
var data = [
{ "Channel": "MTV Rocks", "HKI": 99.104700, "LTI": 98.760400 },
{ "Channel": "MTV3 HD", "HKI": 99.724600, "LTI": 99.724600 },
{ "Channel": "MTV3", "HKI": 100.000000, "LTI": 100.000000 },
];
var channels = [['Channel', 'HKI (%)', {type: 'string', role: 'tooltip', p: {html: true}}, 'LTI (%)', {type: 'string', role: 'tooltip', p: {html: true}}]];
// Loop through each data and populate the array.
$.each(data, function (index, value) {
channels.push([
value.Channel,
value.HKI,
'<div class="ggl-tooltip"><div>' + value.Channel + '</div><div>' + value.HKI + '</div></div>',
value.LTI,
'<div class="ggl-tooltip"><div>' + value.Channel + '</div><div>' + value.LTI + '</div></div>'
]);
});
// Set chart Options.
var options = {
title: 'DVB-C Availability (HKI & LTI)',
series: {
0: {color: '#ff3385', lineWidth: 5, pointSize: 5},
1: {color: '#000000', lineWidth: 1, pointSize: 3},
},
vAxis: {title: "Availability (%)", maxValue: 100},
hAxis : {title: "Channels", showTextEvery:1, textStyle : {fontSize: 8, bold:'true'}, slantedText:true, slantedTextAngle:45},
chartArea:{left: 70, top:50, right:40, width:"90%", height:"70%"},
tooltip: {isHtml: true, trigger: 'both'},
legend: {position: 'top', textStyle: { color: '#555', fontSize: 14}}
};
// Create DataTable and add the array to it.
var figures = google.visualization.arrayToDataTable(channels)
// Define the chart type (LineChart) and the container (a DIV in our case).
var chart = new google.visualization.LineChart(document.getElementById('chart'));
chart.draw(figures, options); // Draw the chart with Options.
}
.ggl-tooltip {
border: 1px solid #E0E0E0;
font-family: Arial, Helvetica;
font-size: 10pt;
padding: 12px 12px 12px 12px;
}
.ggl-tooltip div {
padding-top: 6px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>
EDIT
if you want to display an external html file as the tooltip,
it may make sense to hide the standard tooltip,
and display the external file 'onmouseover'
see following working snippet for an example...
google.charts.load('current', { packages: ['corechart'] });
google.charts.setOnLoadCallback(drawLineChart);
function drawLineChart() {
var data = [
{ "Channel": "MTV Rocks", "HKI": 99.104700, "LTI": 98.760400 },
{ "Channel": "MTV3 HD", "HKI": 99.724600, "LTI": 99.724600 },
{ "Channel": "MTV3", "HKI": 100.000000, "LTI": 100.000000 },
];
var channels = [['Channel', 'HKI (%)', 'LTI (%)']];
// Loop through each data and populate the array.
$.each(data, function (index, value) {
channels.push([
value.Channel,
value.HKI,
value.LTI
]);
});
// Set chart Options.
var options = {
title: 'DVB-C Availability (HKI & LTI)',
series: {
0: {color: '#ff3385', lineWidth: 5, pointSize: 5},
1: {color: '#000000', lineWidth: 1, pointSize: 3},
},
vAxis: {title: "Availability (%)", maxValue: 100},
hAxis : {title: "Channels", showTextEvery:1, textStyle : {fontSize: 8, bold:'true'}, slantedText:true, slantedTextAngle:45},
chartArea:{left: 70, top:50, right:40, width:"90%", height:"70%"},
tooltip: {trigger: 'none'},
legend: {position: 'top', textStyle: { color: '#555', fontSize: 14}}
};
// Create DataTable and add the array to it.
var figures = google.visualization.arrayToDataTable(channels)
// Define the chart type (LineChart) and the container (a DIV in our case).
var chart = new google.visualization.LineChart(document.getElementById('chart'));
var frame = document.getElementById('tooltip');
// hide external html on mouse out
google.visualization.events.addListener(chart, 'onmouseout', function () {
frame.className = 'hidden';
});
// display external html on mouse over
google.visualization.events.addListener(chart, 'onmouseover', function (props) {
if (props.row === null) {
return;
}
var chartLayout = chart.getChartLayoutInterface();
var bounds = chartLayout.getBoundingBox('point#' + (props.column - 1) + '#' + props.row);
frame.style.left = bounds.left + 'px';
frame.style.top = bounds.top + 'px';
// replace this
frame.src = 'https://www.december.com/html/demo/hello.html';
// with this
//frame.src = '../' + figures.getColumnLabel(props.column) + (props.row + 1) + '.html';
frame.className = 'tooltip';
});
chart.draw(figures, options);
}
.hidden {
display: none;
visibility: hidden;
}
.tooltip {
background-color: #ffffff;
position: absolute;
height: 200px;
width: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>
<iframe class="hidden" id="tooltip"></iframe>

Kendo grid binding not working in angularjs

I am trying to bind list which i am populating after receiving response from API. I can see the objects into the list but i still didn't understand why kendo grid is not binding datasource. i have code as below.
vm.getAccounts = function () {
acctSearchService.searchAccounts(null, vm.AccountSearchModel)
.then(getAccountsSuccess, getAccountsFailure);
}
vm.accountGridData = [];
function getAccountsSuccess(response) {
vm.accountGridData.push(response.model);
return vm.accountGridData;
}
i am getting result into vm.accountGridData after receiving response from API call and i am trying to bind that to datasource of kendo grid as below.
$("#grid").kendoGrid({
dataSource: { data: vm.accountGridData },
height: 550,
filterable: true,
sortable: true,
pageable: true,
columns: vm.mainGridColumns
});
Do i need to do anything else to get the data ?
You need to create a directive like this:
app.directive('myDirective', function () {
return {
restrict: 'EA',
scope: {},
template: [].join(''),
controllerAs: 'vm',
controller: function () {
var vm = this;
vm.getAccounts = function () {
acctSearchService.searchAccounts(null, vm.AccountSearchModel).then(getAccountsSuccess, getAccountsFailure);
}
vm.accountGridData = [];
function getAccountsSuccess(response) {
vm.accountGridData.push(response.model);
return vm.accountGridData;
}
},
link: function () {
$("#grid").kendoGrid({
dataSource: { data: vm.accountGridData },
height: 550,
filterable: true,
sortable: true,
pageable: true,
columns: vm.mainGridColumns
});
}
};
});
And in your html:
<div my-directive></div>
<div id="grid"></div>
You dont need data property in your datasource if you don't implement custom read function for it.
Datasource property should be an array or kendo-datasource object.
Try this:
$("#grid").kendoGrid({
dataSource: vm.accountGridData,
height: 550,
filterable: true,
sortable: true,
pageable: true,
columns: vm.mainGridColumns
});
And checkout grid documentation: http://docs.telerik.com/kendo-ui/api/javascript/ui/grid
Finally i found the way after fighting. it's in simple one step.
<!DOCTYPE html>
<html>
<head>
<base href="http://demos.telerik.com/kendo-ui/grid/angular">
<style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style>
<title></title>
<link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.3.1118/styles/kendo.common-bootstrap.min.css" />
<link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.3.1118/styles/kendo.bootstrap.min.css" />
<link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.3.1118/styles/kendo.bootstrap.mobile.min.css" />
<link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.3.1118/styles/kendo.silver.min.css" />
<link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.3.1118/styles/kendo.silver.mobile.min.css" />
<script src="//kendo.cdn.telerik.com/2016.3.1118/js/jquery.min.js"></script>
<script src="//kendo.cdn.telerik.com/2016.3.1118/js/angular.min.js"></script>
<script src="//kendo.cdn.telerik.com/2016.3.1118/js/kendo.all.min.js"></script>
</head>
<body>
<div id="example" ng-app="KendoDemos">
<div ng-controller="MyCtrl">
<kendo-grid k-scope-field="grid" options="mainGridOptions"></kendo-grid>
</div>
</div>
<script>
angular.module("KendoDemos", [ "kendo.directives" ])
.controller("MyCtrl", function($scope, $http){
$scope.data = new kendo.data.ObservableArray([]);
$http({
method: 'GET',
type:"json",
url: '//jsonplaceholder.typicode.com/posts'
}).then(function successCallback(response) {
$scope.grid.dataSource.data(response.data);
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
$scope.mainGridOptions = {
dataSource: {
data: $scope.data,
pageSize: 5
},
sortable: true,
pageable: true,
filterable: {
mode: "row"
},
resizable: true,
columns: [{
field: "userId",
title: "userId",
width: "120px"
},{
field: "id",
title: "ID",
width: "120px"
},{
field: "title",
width: "120px"
},{
field: "body",
width: "120px"
}]
};
})
</script>
</body>
</html>

Using jqGrid with .NET MVC Json Data won't load -columns showing ok

I am having a tough time loading data from .NET MVC 4.0.01 and I have been doing extensive research on the JQgrid site and documentation but cannot seem to find the issue.
And in my Grid (I'm using jqGrid 4.9.2)
$(function () {
gridMs = $("#jqGridMSats").jqGrid({
url: "Status/GetMissingItems",
//contentType: "application/json",
datatype: "json",
loadError: function (xhr, status, error) { alert(status + " " + error); },
mtype: "GET",
colNames: ["SattId", "SattUId", "SattScannedId", "SattName",
"SattAntenna", "SattCount", "SattFirstDiscovered", "SattLastSeen", "ZoneUId",
"ContainerId", "SattPlanUId", "Details"],
colModel: [{ name: "SattId", index: "SattId", hidden: false, width: 100 },
{ name: "SattUId", index: "SattUId", align: 'left', hidden: true, search: false, sortable: true, width: 75 },
{ name: "SattScannedId", index: "SattScannedId", align: 'left', search: false, sortable: true, width: 75 },
{ name: "SattName", index: "SattName", align: 'center', hidden: false, width: 30 },
{ name: "SattAntenna", index: "SattAntenna", align: 'center', hidden: false, width: 30 },
{ name: "SattCount", index: "SattCount", align: 'center', hidden: false, width: 30 },
{ name: "SattFirstDiscovered", index: "SattFirstDiscovered", align: 'center', hidden: true, formatter: 'date',
formatoptions: { newformat: "d-M-Y" }, search: true, sortable: true, width: 80,
searchoptions: {
dataInit: function (element) {
$(element).daterangepicker({
id: 'Discovered',
dateFormat: 'yy/mm/dd',
minDate: new Date(2014, 0, 1),
maxDate: new Date(2025, 0, 1),
showOn: 'focus',
onSelect: function () {
//var startDate = $(el).val().start;
//var endDate = $(el).val().end;
//alert("Start: " + startDate + " End: " + endDate);
}
});
},
// show search options
sopt: ["ge", "le", "eq"] // ge = greater or equal to, le = less or equal to, eq = equal to
}
},
{
name: "SattLastSeen", index: "SattLastSeen", align: 'center', stype: 'text', formatter: 'date',
formatoptions: { newformat: "d-M-Y" }, search: true, sortable: true, width: 90,
searchoptions: {
// dataInit is the client-side event that fires upon initializing the toolbar search field for a column
// use it to place a third party control to customize the toolbar
dataInit: function (el) {
$(el).daterangepicker({
id: 'drpLS',
dateFormat: 'yy/mm/dd',
minDate: new Date(2014, 0, 1),
maxDate: new Date(2025, 0, 1),
showOn: 'focus',
onClose: function () {
var misDate = $(el).val();
var dtArray = misDate.split('-');
var startdate = dtArray[0].trim();
var endDate = dtArray[1].trim();
}
});
},
// show search options
sopt: ["ge", "le", "eq"] // ge = greater or equal to, le = less or equal to, eq = equal to
}
},
{ name: "ZoneUId", index: "ZoneUId", align: 'center', sortable: true, width: 60 },
{ name: "ContainerId", index: "ContainerId", align: 'center', hidden: false, sortable: true, width: 60 },
{ name: "SattPlanUId", index: "SattPlanUId", align: 'center', hidden: true, sortable: true, width: 60 },
{ name: "Details", index: "Details", align: 'center', width: 30, hidden: true, search: false, formatter: function (cellvalue) {
return "<img src='../../Content/finder.png' alt='Locate sat' />";
}
}
],
width: 770,
height: 'auto',
loadonce: true,
//rowNum: 11,
pager: "#jqGridPagerMSatts",
viewrecords: true,
caption: "Missing",
gridview: true,
autoencode: true,
footerrow: true,
loadComplete: function () { alert("loaded"); },
jsonReader: {
root: "rows",
repeatitems: false,
page: function (obj) { return 1; }, // page as 1
total: function (obj) { return 1; }, // total as 1
records: function (obj) { return obj.length; }
},
onCellSelect: function (rowid, index) {
var cm = gridMs.jqGrid('getGridParam', 'colModel');
if (cm[index].name == 'Details' && satValue.indexOf("----") == -1) {
alert('test');
}
},
});
gridMs.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, searchOperators: true });
gridMs.navGrid('#jqGridPagerMSatts', { edit: false, add: false, del: false, search: false });
});
My client side references:
<link href="<%= Url.Content("~/Scripts/jqGridM/css/ui.jqgrid.css") %>" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="<%= Url.Content("~/Scripts/jqGridM/js/i18n/grid.locale-en.js") %>" ></script>
<script type="text/javascript" src="<%= Url.Content("~/Scripts/jqGridM/js/jquery.jqGrid.min.js") %>" ></script>
My columns load and the total records show. But cannot get the data to show. I've tried changing the controller to return a JavascriptSerializer format but still the same. I also removed the dates column thinking maybe it's a format issue but still the same results- no data shown. I get no errors at all when checking (Response) from Chrome. I have another grid in the same page which I can push dynamic data to just fine however loading the data from MVC Action is the problem. Is there something I am missing in my code? Any help would be greatly appreciated.
Here is how the FULL page renders in Chrome. If I invoke the missingTagGrid function first that Grid shows the data fine. Then if I select the resetGrid afterwards it loads fine too. If I select the resetGrid function first however the other grid won't load but it will show the colums and total pages....no errors in Chrome.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1">
<title></title>
<link href="/Content/Css/Reset.css" rel="stylesheet" type="text/css" />
<link href="/Content/Css/History.css" rel="stylesheet" type="text/css" />
<link href="/Content/Css/AnyTime.css" rel="stylesheet" type="text/css" />
<link href="/Content/Inventory/jquery-ui.css" rel="stylesheet" type="text/css" />
<link href="/Content/Inventory/ui.daterangepicker.css" rel="stylesheet" type="text/css" />
<link href="/Scripts/jqGridM/css/ui.jqgrid.css" rel="stylesheet" type="text/css" />
<link href="/Content/Css/spectrum.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="/Scripts/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="/Scripts/spectrum.js"></script>
<link type="text/css" href="/Content/telerik.common.min.css" rel="stylesheet"/>
<link type="text/css" href="/Content/telerik.vista.min.css" rel="stylesheet"/>
</head>
<body>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
var inventoryData = [];
var missingData = [];
var mydata;
var rowMissing = 0;
var rowTotals;
var rowMissingMis = 0;
var rowtotalsMis;
var isMissing = false;
var mydata = [];
var newCompArray = [];
var machineName = 'bcd44e4c';
var registeredGrp = 'ACME Lgstks';
</script>
<form method="post" action="Status" id="form1"><div>
<div id="timeDiv"></div>
<div id="stsGrid" style="float: left;">
<div id="tagStatus" style="width: 560px;">
<div id="invGrid">
<table id="jqGrid"></table>
<div id="jqGridPager"></div></div>
<div id="misGrid">
<table id="jqGridMTags"></table>
<div id="jqGridPagerMTags"></div>
</div>
</div>
</div>
</div>
<div style="clear: both;">
</div>
</form>
<div id="removeChildModal" class="jqmWindow section">
</div>
<script type="text/javascript">
$('#misGrid').hide();
</script>
<script type="text/javascript">
function resetGrid() {
$('#misGrid').hide();
$('#invGrid').show();
var gridData;
var rowIds;
var messenger = $.connection.messenger;
$("#jqGridMTags").hide();
gridInv = null;
//<![CDATA[
$(function () {
'use strict';
var mydata = [], //Need this for SignalR
gridInv = $("#jqGrid");
gridInv.jqGrid({
datatype: "jsonstring",
datastr: inventoryData,
colNames: ["Antenna", "Content", "Count", "Direction", "Discovered", "Duration", "EPC", "Freq","LastSeen", "Name", "Pack", "RSSI", "Size", "Speed", "Title", "Type", "Zone", "Find"],
colModel: [{name: "Antenna", index: "Antenna", key: true, hidden: true, width: 100, cellattr: function (rowId) {if (rowId < 5) { return 'colspan=8'; }}
},
{ name: "Content", index: "Content", align: 'left', search: false, sortable: true, width: 75 },
{ name: "Count", index: "Count", align: 'center', search: false, sortable: true, width: 40 },
{ name: "Direction", index: "Direction", align: 'center', hidden: true, width: 30 },
{ name: "Discovered", index: "Discovered", align: 'center', stype: 'text', search: true, sortable: true, width: 80,
searchoptions: {
// dataInit is the client-side event that fires upon initializing the toolbar search field for a column
// use it to place a third party control to customize the toolbar
dataInit: function (element) {$(element).daterangepicker({id: 'Discovered',dateFormat: 'yy/mm/dd',minDate: new Date(2014, 0, 1),maxDate: new Date(2025, 0, 1),
showOn: 'focus'
});
},
// show search options
sopt: ["ge", "le", "eq"] // ge = greater or equal to, le = less or equal to, eq = equal to
}
},
{ name: "Duration", index: "Duration", align: 'center', hidden: true, width: 60 },
{ name: "EPC", index: "EPC", align: 'center', sortable: true, width: 140 },
{ name: "Freq", index: "Freq", align: 'center', hidden: true, sortable: true, width: 50 },
{
name: "LastSeen", index: "LastSeen", align: 'center', stype: 'text', search: true, sortable: true, width: 80,
searchoptions: {
dataInit: function (element) {$(element).daterangepicker({id: 'LastSeen',dateFormat: 'yy/mm/dd',minDate: new Date(2014, 0, 1),maxDate: new Date(2025, 0, 1),showOn: 'focus'});},
// show search options
sopt: ["ge", "le", "eq"] // ge = greater or equal to, le = less or equal to, eq = equal to
}
},
{ name: "Name", index: "Name", align: 'center', sortable: true, width: 50 },
{ name: "Pack", index: "Pack", align: 'center', hidden: true, sortable: true, width: 60 },
{ name: "RSSI", index: "RSSI", align: 'center', hidden: true, sortable: true, width: 50 },
{ name: "Size", index: "Size", align: 'center', hidden: true, sortable: true, width: 60 },
{ name: "Speed", index: "Speed", align: 'center', hidden: true, sortable: true, width: 60 },
{ name: "Title", index: "Title", align: 'center', hidden: true, sortable: true, width: 60 },
{ name: "Type", index: "Type", align: 'center', width: 33, search: false, formatter: function (cellvalue) {
if (cellvalue == "----") return "----";
if (cellvalue == "None" || cellvalue === 'undefined' || cellvalue == '')
return "<img src='../../Scripts/Tree/skin/0000.png' alt='Locate tag' />";
else
return "<img src='../../Scripts/Tree/skin/" + cellvalue + ".png' alt='Locate tag' />";
}
},
{ name: "Zone", index: "Zone", align: 'center', search: true, sortable: true, width: 50 },
{ name: "Find", index: "Find", align: 'center', width: 25, search: false, formatter: function (cellvalue) {
if (cellvalue == "----") return "----";
else
return "<img src='../../Content/finder.png' alt='Locate tag' />";
}
}
],
width: 770,
height: 428,
gridview: true,
rowattr: function (rd) {
if (rd.Find === "----") { // verify it's Zone parent
return { "class": "zoneHdr" };
}
else
return { "class": "selected-row" };
},
loadonce: true,
rowNum: 11,
pager: "#jqGridPager",
sortname: 'Antenna',
treeGrid: true,
treeGridModel: 'adjacency',
treedatatype: "jsonstring",
ExpandColumn: 'Content',
viewrecords: true,
caption: "Inventory List",
footerrow: true,
grouping: false,
jsonReader: {
repeatitems: false,
root: function (obj) { return obj; },
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.length; }
},
onCellSelect: function (rowid, index) {
var tagValue = gridInv.jqGrid('getCell', rowid, 'Title');
var zneValue = gridInv.jqGrid('getCell', rowid, 'Zone');
var cm = gridInv.jqGrid('getGridParam', 'colModel');
if (cm[index].name == 'Find' && tagValue.indexOf("----") == -1) {
localStorage.setItem("tagStore", tagValue);
localStorage.setItem("zneStore", zneValue);
}
window.location = "/Package";
},
});
gridInv.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, searchOperators: true });
gridInv.navGrid('#jqGridPager', { edit: false, add: false, del: false, search: false });
gridInv.navButtonAdd('#jqGridPager', {
caption: "Click to show missing tags",
buttonicon: "ui-icon-tag",
position: "last",
onClickButton: function () {
alert("Deleting Row");
}
});
});
gridData = $('#jqGrid').jqGrid('getRowData');
for (var key in gridData[0]) {rowIds = $('#jqGrid').jqGrid('getCol', key, true);
break;
}
if (typeof gridData != "undefined" && typeof rowIds != "undefined") {
$.each(gridData, function (id) {var $row = $('#' + rowIds[id].id);
$row.show();});
}
rowTotals = ($('#jqGrid').getGridParam('records') - 4);
rowMissing = 0;
$('#jqGrid').jqGrid("footerData", "set", { Content: "<span style='color:red'>Total Missing:</span>", Count: "<span style='color:red'>" + rowMissing + "</span>", LastSeen: "Total Inventoried:", Name: rowTotals });
$("#jqGrid").trigger("reloadGrid");
messenger.server.broadCastReaderConfig(false, '');
//
}
///Missing Tags
function missingTagGrid() {
$('#misGrid').show();
$('#invGrid').hide();
var gridMs = null;
//<![CDATA[
$(function () {
gridMs = $("#jqGridMTags").jqGrid({
url: "Status/GetMissingItems",
//contentType: "application/json",
datatype: "json",
loadError: function (xhr, status, error) { alert(status + " " + error); },
mtype: "GET",
colNames: ["TagId", "TagUId", "TagScannedId", "TagName", "TagAntenna", "TagCount", "TagFirstDiscovered", "TagLastSeen", "ZoneUId", "ContainerId", "FloorplanUId", "Details"],
colModel: [{ name: "TagId", index: "TagId", hidden: false, width: 100 },
{ name: "TagUId", index: "TagUId", align: 'left', hidden: true, search: false, sortable: true, width: 75 },
{ name: "TagScannedId", index: "TagScannedId", align: 'left', search: false, sortable: true, width: 75 },
{ name: "TagName", index: "TagName", align: 'center', hidden: false, width: 30 },
{ name: "TagAntenna", index: "TagAntenna", align: 'center', hidden: false, width: 30 },
{ name: "TagCount", index: "TagCount", align: 'center', hidden: false, width: 30 },
{
name: "TagFirstDiscovered", index: "TagFirstDiscovered", align: 'center', hidden: true, formatter: 'date',
formatoptions: { newformat: "d-M-Y" }, search: true, sortable: true, width: 80,
searchoptions: { dataInit: function (element) {
$(element).daterangepicker({
id: 'Discovered',
dateFormat: 'yy/mm/dd',
minDate: new Date(2014, 0, 1),
maxDate: new Date(2025, 0, 1),
showOn: 'focus',
onSelect: function () {
}
});
},
sopt: ["ge", "le", "eq"] // ge = greater or equal to, le = less or equal to, eq = equal to
}
},
{ name: "TagLastSeen", index: "TagLastSeen", align: 'center', stype: 'text', formatter: 'date',
formatoptions: { newformat: "d-M-Y" }, search: true, sortable: true, width: 90,
searchoptions: { dataInit: function (el) {
$(el).daterangepicker({
id: 'drpLS',
dateFormat: 'yy/mm/dd',
minDate: new Date(2014, 0, 1),
maxDate: new Date(2025, 0, 1),
showOn: 'focus',
onClose: function () {
var misDate = $(el).val();
var dtArray = misDate.split('-');
var startdate = dtArray[0].trim();
var endDate = dtArray[1].trim();
}
});
},
sopt: ["ge", "le", "eq"] // ge = greater or equal to, le = less or equal to, eq = equal to
}
},
{ name: "ZoneUId", index: "ZoneUId", align: 'center', sortable: true, width: 60 },
{ name: "ContainerId", index: "ContainerId", align: 'center', hidden: false, sortable: true, width: 60 },
{ name: "FloorplanUId", index: "FloorplanUId", align: 'center', hidden: true, sortable: true, width: 60 },
{ name: "Details", index: "Details", align: 'center', width: 30, hidden: true, search: false, formatter: function (cellvalue) {
return "<img src='../../Content/finder.png' alt='Locate tag' />";
}
}
],
width: 770,
height: 'auto',
loadonce: true,
pager: "#jqGridPagerMTags",
viewrecords: true,
caption: "Missing",
gridview: true,
autoencode: true,
footerrow: true,
jsonReader: {
root: "rows",
repeatitems: false,
page: function (obj) { return 1; }, // page as 1
total: function (obj) { return 1; }, // total as 1
records: function (obj) { return obj.length; }
},
onCellSelect: function (rowid, index) {
var cm = gridMs.jqGrid('getGridParam', 'colModel');
if (cm[index].name == 'Details' && tagValue.indexOf("----") == -1) {
alert('Pop up to decribe missing tag in detail');
}
},
});
gridMs.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, searchOperators: true });
gridMs.navGrid('#jqGridPagerMTags', { edit: false, add: false, del: false, search: false });
});
}
<!-- other content -->
<script type="text/javascript" src="/Scripts/jquery-1.7.1.js"></script>
<script type="text/javascript" src="/Scripts/telerik.common.min.js"></script>
<script type="text/javascript" src="/Scripts/telerik.list.min.js"></script>
<script type="text/javascript" src="/Scripts/SignalR.StatusHub.js"></script>
<script type="text/javascript" src="/Scripts/trirand/jquery.jqDropDownList.min.js" ></script>
<script type="text/javascript" src="/Scripts/trirand/jquery.jqDatePicker.min.js" ></script>
<script type="text/javascript" src="/Scripts/trirand/jquery.jqAutoComplete.min.js" ></script>
<script type="text/javascript" src="/Scripts/jqGridM/js/i18n/grid.locale-en.js" ></script>
<script type="text/javascript" src="/Scripts/jqGridM/js/jquery.jqGrid.min.js" ></script>
<script type="text/javascript" src="/Scripts/jqGridM/js/jquery.jqGrid.src.js" ></script>
<script type="text/javascript" src="/Scripts/jquery-ui-1.10.4.custom.js"></script>
<script type="text/javascript" src="/Scripts/jquery.ui.dialog.js"></script>
<script type="text/javascript" src="/Scripts/InventoryScripts/date.js"></script>
<script type="text/javascript" src="/Scripts/InventoryScripts/daterangepicker.jQuery.js"></script>
<script type="text/javascript" src="/Scripts/jquery.signalR-2.1.2.js"></script>
<script type="text/javascript" src="/signalr/hubs"></script>
</body>
</html>
You use wrong order of included JavaScript data and you placed some HTML element on the wrong place. For example you placed in <head> of the page the following JavaScript files
<script type="text/javascript" src="/Scripts/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="/Scripts/spectrum.js"></script>
You have to include jQuery before jquery-1.11.0.min.js which depends from jQuery.
The next error: you included two different version of the same file. For example, You included jquery-1.11.0.min.js in the <head> and then placed jquery-ui-1.10.4.custom.js in the <body>. It's wrong. In the same way it's wrong to include both non-minimized and minimized version of the same JavaScript library. See jquery.jqGrid.src.js included directly after jquery.jqGrid.min.js.
You used jquery-1.7.1.js which is not an error, but I would strictly recommend you don't uses such retro version of jQuery. Instead of that you should use jQuery 1.11.3 or jQuery 2.1.4 if you don't need to support old web browsers IE6, IE7 and IE8.
I places <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> inside of <body>. It's wrong. All <meta> should be included directly after <title>. Don't forget to include
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
which is required to prevent using compatibility mode of IE.
Now about the code itself. It's difficult to read the code divided into many separate <script></script> parts. Moreover the code is either not full or some important functions will be not called or be called in the wrong order. You should first include jQuery, then include jqGrid and only after that you can use jqGrid method. Another problem: you define resetGrid and missingTagGrid function, but never call there (using resetGrid(); or missingTagGrid();).
One more problem: The code
$(function () {...});
is the short form of document ready function:
$(document).ready(function () {...});
which wait till the document which includes the <> is loaded and then execute the function inside of it (... part). In the case the usage of document ready inside of <body> (inside of the document) is not a good idea. You should wither remove $(function () { part, but place the code after HTML parts which you used in the handler (after <table id="jqGrid"></table> for example) or better to move the inside of <head>. Just examine once more the demo, which I posted before in the comment, under the aspect of the order included JavaScript files, the code, <head> and and <body>.
One more important aspect of JavaScript language: you should define variables of function inside of another outer function if it's possible. If you define variables directly on the top of the script like
<script type="text/javascript">
var inventoryData = [];
var missingData = [];
var mydata;
var rowMissing = 0;
var rowTotals;
var rowMissingMis = 0;
var rowtotalsMis;
var isMissing = false;
var mydata = [];
var newCompArray = [];
var machineName = 'bcd44e4c';
var registeredGrp = 'ACME Lgstks';
</script>
then you define global variables. It makes potential conflicts with another code which you included. For example if you would define $ = 0 or jQuery = null in the way you will break the code of jQuery and and jQuery plugins. It's important to understand additionally that the above script not only define global variables, it assign new properties to the global window object. You can easy verify that window object have rowMissing property now and the value of the property is 0. It would be much better to move the code inside of some function. For example the code
<script type="text/javascript">
$(function () {
var rowMissing = 0, rowTotals;
...
rowTotals = ($('#jqGrid').getGridParam('records') - 4);
$('#jqGrid').jqGrid("footerData", "set", {
Content: "<span style='color:red'>Total Missing:</span>",
Count: "<span style='color:red'>" + rowMissing + "</span>",
LastSeen: "Total Inventoried:",
Name: rowTotals
});
...
});
</script>
is much better. It defined local variables rowMissing and rowTotals existing only inside the function and it uses the variables inside of the function. In the way one will have no conflicts.
Ok, the biggest problem was Telerik's script register was embedding the older version of Jquery (jquery-1.7.1.js). I didn't notice it until you pointed it out. It's one of those things that Telerik does undercover so it was easy to miss. Great observation on the bad references, order and global vars, fixed those also. Thanks for all your help Oleg..you're truly awesome. Works like a charm now!

adding live data to highstock Using json file

I'm trying to update a highcharts highstock chart with live data from a json file on my server.
now I have a chart that gets its data from a json file (that I create with php that requests the data from my MySQL database) like so:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>OKcoin Price LTCCNY</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$.getJSON('json/lastTradesOkcoinLTCCNY.json', function(data) {
Highcharts.setOptions({
global: {
useUTC: false
}
});
// create the chart
$('#container').highcharts('StockChart', {
rangeSelector : {
selected : 1
},
title : {
text : 'OkCoin Price LTCCNY'
},
rangeSelector: {
buttons: [{
type: 'hour',
count: 1,
text: '1h'
}, {
type: 'hour',
count: 6,
text: '6h'
}, {
type: 'hour',
count: 12,
text: '12h'
}, {
type: 'hour',
count: 24,
text: '24h'
}, {
type: 'day',
count: 3,
text: '3d'
}, {
type: 'day',
count: 7,
text: '7d'
}, {
type: 'all',
text: 'All'
}],
selected: 2
},
xAxis: {
gridLineWidth: 1,
title: {
enabled: true,
text: 'Time',
style: {
fontWeight: 'normal'
}
}
},
yAxis: [{
title: {
text: 'Price LTCCNY'
},
gridLineWidth: 1,
minorTickInterval: 'auto',
minorTickColor: '#FEFEFE',
labels: {
align: 'right'
}
}],
plotOptions: {
series: {
lineWidth: 1
}
},
tooltip: {
valueDecimals: 5,
valuePrefix: '$ '
},
series : [{
name : 'LTCCNY Price',
data : data,
dataGrouping : {
units : [
['minute',
[1, 5, 10, 15, 30]
], ['hour', // unit name
[1]
]
]
}
}]
});
});
});
</script>
</head>
<body>
<script src="../Highstock/js/highstock.js"></script>
<script src="../Highstock/js/modules/exporting.js"></script>
<div id="container" style="height: 500px; min-width: 500px"></div>
</body>
</html>
So far no problems, I get a chart from the json file. But of course it doesn't update if new data becomes available (only if I reload the page) .
What I want to do is after loading this chart, add live data to it as it becomes available.
something like this example, but instead of random data the chart will be updated with data from a (second) live updating json file on my webserver. The json file will be created by php (this part is working just fine) But I can't figure out how to add the data from the json file to the my existing highstock chart.
I also found
this this example on highcharts.com and that more or less does what I try to do, but I can't integrate the 'requestData' function into my existing chart.
So what I want to do is use the 'requestData' function from the second example with the high stock chart I already have. My second json file (with the live data) looks the same as in the second example (timestamp, price):
[1389022968000,173.3]
Can anyone help me a bit?
nevermind, I figured it out myself...
here's my solution:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>OKCoin LTCCNY Price</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
var chart; // global
function requestData() {
$.ajax({
url: 'tickOkCoinLTCCNY.json',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 2; // shift if the series is longer than 20
// add the point
chart.series[0].addPoint(eval(point), true, shift);
// call it again after one second
setTimeout(requestData, 10000);
},
cache: false
});
}
$(function() {
$.getJSON('../okcoin/json/lastTradesOkcoinLTCCNY.json', function(data) {
// set the allowed units for data grouping
var groupingUnits = [[
'minute', // unit name
[1,5,15,30] // allowed multiples
], [
'hour',
[1, 2, 3, 4, 6]
]];
// create the chart
chart = new Highcharts.StockChart({
chart: {
renderTo: 'container',
events: {
load: requestData
}
},
rangeSelector: {
buttons: [{
type: 'hour',
count: 1,
text: '1h'
}, {
type: 'hour',
count: 6,
text: '6h'
}, {
type: 'hour',
count: 12,
text: '12h'
}, {
type: 'hour',
count: 24,
text: '24h'
}, {
type: 'day',
count: 3,
text: '3d'
}, {
type: 'day',
count: 7,
text: '7d'
}, {
type: 'all',
text: 'All'
}],
selected: 2
},
title: {
text: 'OKCoin LTCCNY Price'
},
xAxis: {
type: 'datetime',
gridLineWidth: 1,
title: {
enabled: true,
text: 'Time',
style: {
fontWeight: 'normal'
}
}
},
yAxis: [{
title: {
text: 'LTCCNY'
},
lineWidth: 2
}],
series: [{
name: 'LTCCNY',
data: data,
dataGrouping: {
units: groupingUnits
}
}]
});
});
});
</script>
</head>
<body>
<script src="../Highstock/js/highstock.js"></script>
<script src="../Highstock/js/modules/exporting.js"></script>
<div id="container" style="height: 500px; min-width: 500px"></div>
</body>
</html>

Highchart not displaying json data

I can't figure out what I'm doing wrong with my Highchart. It's supposed to read a json array, (really just a date, and a y value and plot it to a chart. However, I can't seem to get any points to plot to a chart. What am I doing wrong?
php code:
$statement = "select count(title) from node where title like 'WEN%'";
$result = mysql_query($statement);
while ($row = mysql_fetch_array($result)) {
$data = $row['count(title)'];
}
$x = time() * 1000;
$y = $data;
$array = array($x,$y);
echo json_encode($array);
html/javascript code:
<p>Chart</p>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto">
<script>
function requestData() {
jQuery.ajax({
url: 'queryp.php',
datatype: 'json',
success: function(point) {
var series = chart.series[0];
// add the point
chart.series[0].addPoint(point, true);
// call it again after one second
setTimeout(requestData, 5000);
},
cache: false
});
}
</script>
<script type="text/javascript">
jQuery(function () {
jQuery(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'spline',
marginRight: 10,
events: {
load: requestData
}
},
title: {
text: 'Live Query Data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
legend: {
enabled: true
},
exporting: {
enabled: false
},
series: [{
name: 'Query Data',
data: []
}]
});
});
});
</script>
</div>
Your series[0] object has no method named addPoint, you should see this in the console.
If you want to append to the data array, just use push
chart.series[0].data.push(point[1]);
The problem is that you are referencing to chart variable, which is not ready yet - you are using load event handler. Use something like this:
function requestData() {
var series;
if(chart.series[0]){
/* all other cases load chart */
series = chart.series[0];
} else {
/* first load chart */
series = this.series[0];
}
jQuery.ajax({
url: 'queryp.php',
datatype: 'json',
success: function(point) {
series.addPoint(point, true);
setTimeout(requestData, 5000);
}
});
}
Also, make sure that values are numbers. Not strings.