Highchart not displaying json data - json

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.

Related

Highcharts with ajax/ json and SQL Server ASP.NET

I am new to Highcharts and Json data. I am trying to draw pretty simple column chart but failing to do so. below is my code.
HTML:
<div id="container"></div>
Javascript:
$(document).ready(function () {
$.ajax({
url: 'HighCharts.aspx/GetServices',
type: 'POST',
async: true,
dataType: 'json',
contentType: 'application/json',
data: '{}',
success: function (response) {
DrawServices(response.d);
},
error: function () {
window.open("ErrorPage.aspx", "_self")
}
});
});
function DrawServices(data) {
debugger;
if (data == null) {
window.open("ErrorPage.aspx","_self")
}
else {
$('#container').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Services Data'
},
xAxis: {
categories: data[0].Name
},
yAxis: {
title: {
text: 'Total Servcies Requested'
}
},
series: data[0].Total
});
}
}
JSON response
[{"Name":"Access the company internet","Total":489},{"Name":"Application Enhancement","Total":97},{"Name":"Catering Service","Total":250},{"Name":"Desktop","Total":350},{"Name":"Development and Consultation","Total":566},{"Name":"Email","Total":175},{"Name":"Laptop","Total":200},{"Name":"Maintenance","Total":32},{"Name":"Push Email","Total":700},{"Name":"Vehicle Sticker","Total":1200}]
Please guide me what i am doing wrong. blank chart is displaying
You can set x-axis type to category and map your data to the format required by Highcharts, for example: [point.name, point.y]
xAxis: {
type: 'category'
},
series: [{
data: data.map(el => [el.Name, el.Total])
}]
Live demo: http://jsfiddle.net/BlackLabel/r709soxe/
API Reference:
https://api.highcharts.com/highcharts/xAxis.type
https://api.highcharts.com/highcharts/series.column.data

How to change value with count data

I have json data with value but instead of display the value i want to display the count of value which is not in my json data. How to make var like select count(*) from ecgvalue?.
This is my code
<script type="text/javascript">
$(function () {
var processed_json = new Array();
$.getJSON('http://localhost:8080/query', function (data) {
// Populate series
for (i = 0; i < data.length; i++) {
processed_json.push([data[i].id_data, data[i].ecgvalue]);
}
// draw chart
$('#container2').highcharts({
chart: {
type: "column"
},
title: {
text: "ECG Graph"
},
xAxis: {
type: 'category',
allowDecimals: false,
title: {
text: "Id Data"
}
},
yAxis: {
title: {
text: "Value"
}
},
series: [{
name: 'ECG value',
data: processed_json
}]
});
});
});
</script>
and this is my json
[{"id_data":1,"ecgvalue":3.3871},{"id_data":2,"ecgvalue":1.56892},{"id_data":3,"ecgvalue":1.60802},{"id_data":4,"ecgvalue":2.09677},{"id_data":5,"ecgvalue":1.99902},{"id_data":6,"ecgvalue":1.97947}]
I want to change value of y axis to count from ecgvalue, is that possible?
If by count you mean how many items are in the processed_json array (as you can with the SQL statement count(*)), then all you need is simply processed_json.length.
Here's a working example using the data you provided: https://jsfiddle.net/brightmatrix/t8pv7csn/
You can then use the processed_json.length however you wish in your code and/or chart options.
<script type="text/javascript">
$(function () {
var processed_json = new Array();
$.getJSON('http://localhost:8080/query', function (data) {
// Populate series
var ecgCount = 0;
for (i = 0; i < data.length; i++) {
ecgCount += data[i].ecgvalue
processed_json.push([data[i].id_data, data[i].ecgvalue]);
}
// draw chart
$('#container2').highcharts({
chart: {
type: "column"
},
title: {
text: "ECG Graph"
},
xAxis: {
type: 'category',
allowDecimals: false,
title: {
text: "Id Data"
}
},
yAxis: {
title: {
text: ecgCount
}
},
series: [{
name: 'ECG value',
data: processed_json
}]
});
});
});
</script>
Is this What you required.

Get current day values from database to plot on highcharts

Hello i am designing a webserver which shows me a power consumption graph from a mysql database. I am a beginner and have written a code with some help that uses ajax calls to fetch the data from the database and plot it on the highcharts. Problem is that I get all the historic values saved in my database but I want only the values of current day to be plotted on the chart. This is my js code:
Highcharts.setOptions({
global: {
useUTC: false
}
});
$('#container').highcharts({
chart: {
type: 'area',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
},
title: {
text: ''
},
xAxis: {
type: 'datetime',
tickPixelInterval: 100
},
yAxis: {
title: {
text: 'POWER'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%d-%m-%Y %H:%M:%S', this.x) + '<br/>' +
Highcharts.numberFormat(this.y);
}
},
legend: {
enabled: true
},
exporting: {
enabled: false
},
series: [{
name: 'Power Consumption',
data: (function () {
var data = [], i, t, d;
var request = {};
request['EndPoint'] = "arduino/charts/analog/fetch";
$.ajax({
type: "POST",
url: "../Server/fyp-processor.php",
data: JSON.stringify(request),
dataType: "json",
async: false,
success: function (result) {
if(result.Code == "1008" && (result.Data != null || result.Data != undefined)) {
for(i = 0; i < result.Data.Historic.length; i++) {
t = result.Data.Historic[i].DateTime.split(/[- :]/);
d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
data.push({
x: d,
y: parseInt(result.Data.Historic[i].Value)
});
}
}
}
});
return data;
}())
}]
});
It calls a fyp-processor php script that contains this code:
else if($postData['EndPoint'] == 'arduino/charts/analog/fetch') {
#result set
$resultSet = null;
#get all historic analog chart data
$results = $db->charts();
if(count($results) > 0) {
foreach($results as $result) {
$resultSet['Historic'][] = $result;
}
}
I would be glad if anyone could help me out to get only current DAY's data and also what changes I can do to it then to get current month and current week's data too.

jqplot json_encode data not rendering line graph

I return these 2 string from controller in codeigniter using json_encode for jqplot line grapgh
here i fetch the data
$(document).ready(function(){
$(".stats").click(function(){
var site_id = $(this).attr("id");
$.ajax({
url: site_url+"statistics/fetch_stats_data/"+site_id,
async: false,
type: "POST",
data: "type=article",
dataType: "json",
success: function(data) {
stat_events_plot_graph(data['activity_events'], data['activity_tricks']);
}
})
});
});
plot data structure returned as php string from above ajax
[["10/21/2014 05:50",1]]
plot ticks structure returned as php string from above ajax
[[1,"Today"]]
when i send this data to the plot the graph is not rendered
function stat_events_plot_graph(activity_events_live, activity_tricks_live) {
var plot2 = $.jqplot('events', [activity_events_live], {
title: 'Events',
seriesDefaults: {
rendererOptions: {
smooth: false,
animation: {
show: true
}
}
},
legend: { show: false },
axes: {
xaxis: {
renderer: $.jqplot.DateAxisRenderer,
tickOptions: { formatString: '%b %#d, %#I %p',angle: -90 }
},
yaxis: {
ticks : activity_tricks_live,
}
},
series: [{ lineWidth: 4,
markerOptions: { style: 'square' }
}],
series: [
{ label: 'Toronto' },
{ label: 'New York' }
],
});
}
how do I convert those 2 strings to work with the line graph ?

URL field not working with flexigrid no response from URL

When I pass the URL I am getting a no response from the url otherwise if I specify the corresponding WCF service page which is included in my project it is working is it any cross domain issue what would be the possible issue
<form id="sform" runat="server">
<table id="flex2" style="display:none"></table>
<script type="text/javascript">
$(document).ready(function () {
var user_id = 1;
var data = { UserID: user_id };
$("#flex2").flexigrid({
useInlineEditor: true,
//singleSelect: true,
rowClick: function (row) {
//var r=this.DataSource.rows[row.rowIndex];
//var p=$(row).offset();
//alert(r[this.DataSource.key]+" "+r.Name+" offset:"+p.top+","+p.left);
//this.grid.inlineEditor.edit(row);
},
url: 'http://192.168.10.91:5001/Service.svc/GetStates',
method: 'POST',
dataType: 'json',
colModel: [
{ display: 'Hours', name: 'hours', width: 40, sortable: true, align: 'center' },
{ display: 'DOC', name: 'doc', width: 180, sortable: true, align: 'left' },
],
searchitems: [
{ display: 'Type', name: 'cmetype' }
],
onError: function (jqXHR, textStatus, errorThrown) {
alert("flexigrid failed " + errorThrown + jqXHR + textStatus);
},
sortname: "type",
sortorder: "asc",
usepager: true,
title: 'States',
useRp: true,
rp: 15,
showTableToggleBtn: true,
width: 800,
height: 200
});
});
//This function adds paramaters to the post of flexigrid. You can add a verification as well by return to false if you don't want flexigrid to submit
function addFormData() {
//passing a form object to serializeArray will get the valid data from all the objects, but, if the you pass a non-form object, you have to specify the input elements that the data will come from
var dt = $('#sform').serializeArray();
$("#flex2").flexOptions({ params: dt });
return true;
}
$('#sform').submit(function () {
$('#flex2').flexOptions({ newp: 1 }).flexReload();
return false;
});
</script>
</form>
Make sure that the svc service is accesibile and that it can accept post requests.
If all works well, check that the response is JSON and is valid.