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.
Related
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.
i had try many diffrent tutarials and examples from http://api.jquery.com/jQuery.getJSON/ and Post data to JsonP and saw many staffs about how to convert json data to jasonP but still i can not do it,is there any one could see how should i pass my data over https within my codes here which i am using highcharts to get data from my domain sql server which is in diffrent server than my webpages host.here is my codes:(i know which i should use ajax request but i dont know how in my case,if anyone know please HELP!) tnx.
getting data by getJASON over data.php which request from sql server to grab data:
var Options;
$(document).ready(function() {
Options = {
chart: {
renderTo: 'container2',
type: 'area',
borderColor: "#3366ff",
borderWidth:5,
zoomType : 'x'
},
title: {
text: 'Total Meeting_Logs Duration of Organization1 '
},
subtitle: {
text: ' '
},
credits:{
enabled:false
},
xAxis: {
categories: [],
labels: {
align: 'center',
x: -3,
y: 20,
//format data based on #datepicker which is html jquery ui date
//picker
formatter: function() {
return Highcharts.dateFormat('%l%p',
Date.parse(this.value +' UTC'));
}
}
},
yAxis: {
title: {
text: ''
}
},
tooltip: {
backgroundColor: '#FCFFC5',
borderColor: 'black',
borderRadius: 10,
borderWidth: 3
},
// Enable for both axes
tooltip: {
crosshairs: [true,true]
},
plotOptions: {
line: {
dataLabels: {
enabled: true
},
enableMouseTracking: false
}
},
series: [{
type: 'area',
name: '',
data: []
}]
}
// here i get my data from data.php within same server
$.getJSON("data.php", function(json){
Options.xAxis.categories = json['category'];
Options.series[0].name = json['name'];
Options.series[0].data = json['data'];
chart = new Highcharts.Chart(Options);
});
});
//this function get user request for input time period and
//update in my domain
$(function() {
$( "#datepicker2" ).datepicker({
dateFormat: "yy-mm-dd",
showOn: "button",
buttonImage: "calendar.gif",
buttonImageOnly: true,
onSelect: function(dateText, inst) {
$.getJSON("data.php?dateparam1="+dateText, function(json){
Options.xAxis.categories = json['category'];
Options.series[0].name = json['name'];
Options.series[0].data = json['data'];
chart = new Highcharts.Chart(Options);
});
}
});
});
data.php:
`
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("moh1368_Mrs_Lemoine", $con);
if (isset($_GET["dateparam"])) {
$sql = mysql_query("SELECT timestamp_value, traffic_count FROM
foot_traffic WHERE timestamp_value LIKE '".$_GET["dateparam"]."%'");
} else {
$sql = mysql_query("SELECT timestamp_value, traffic_count FROM
foot_traffic WHERE timestamp_value LIKE '2013-02-01%'");
}
$result['name'] = 'Foot Traffic Count';
while($r = mysql_fetch_array($sql)) {
$datetime = $r['timestamp_value'];
$result['category'][] = $datetime;
$result['data'][] = $r['traffic_count'];
}
print json_encode($result, JSON_NUMERIC_CHECK);
mysql_close($con);
?>`
I am trying to display csv data in the tooltip of the Highcharts.
Data:
Time,Users,AVG_Sec,Volume,ServerName,InstanceName
11:35 AM ,59,.863,664,server1,int123
11:35 AM ,43,.659,392,server2,int123
11:35 AM ,46,1.347,442,server3,int124
11:35 AM ,49,1.164,702,server2,int125
I am able to display users,avg_sec and volume in the graph.
Please let me know if i can dsplay the servername and instance name in the graph as bars/columns else at least show them in tool tip.
The code so far:
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Last Hourly All'
},
tooltip:{
formatter:function(){
return '<b>' + this.series.name + '</b>' +
'<br/><b>X Value:</b> ' + this.x +
'<br/><b>Y Value:</b> ' + this.y +
'<br/><b>Other Data:</b> ' + this.point.ServerName;
}
},
credits: {
enabled: false
},
xAxis: {
categories: [],
labels: {
rotation: -90
}
},
yAxis:[{
startOnTick: false,
title: {
text: 'No of Transactions'
}
}, {
opposite: true,
title: {
text: 'Response Time'
}
}, {
opposite: true,
title: {
text: 'Volume'
}
}, {
opposite: true,
title: {
text: 'Server Name'
}
}, {
opposite: true,
title: {
text: 'Instance Name'
}
}
],
series: []
};
//try.csv
$.get('data/lastHrlyAllTZ1.csv', function(data) {
// Split the lines
var lines = data.split('\n');
//variable declaration
var series = {
data: [],
type: 'spline',
color: '#336633'
};
var series1 = {
yAxis: 1,
data: [],
color: '#FF3399'
};
var series2 = {
yAxis: 2,
data: [],
color: '#9900FF'
};
var series3 = {
yAxis: 3,
data: [],
color: '#660066'
};
var series4 = {
yAxis: 4,
data: [],
color: '#CC99CC'
};
$.each(lines, function(lineNo, line) {
var items = line.split(',');
// header line contains categories
if (lineNo == 0) {
series1.name = items[1];
series.name = items[2];
series2.name = items[3];
series3.name = items[4];
series4.name = items[5];
}
// the rest of the lines contain data with their name in the first position
else {
$.each(items, function (itemNo, item) {
if (itemNo == 0) {
options.xAxis.categories.push(item);
} else if (itemNo == 1) {
//console.log(parseFloat(item));
series1.data.push(parseFloat(item));
} else if(itemNo == 2){
series.data.push(parseFloat(item));
} else if(itemNo == 3){
series2.data.push(parseFloat(item));
}
else if(itemNo == 4){
//alert(item);
series3.data.push(item);
}
else if(itemNo == 5){
series4.data.push(item);
}
});
}
});
options.series.push(series1);
options.series.push(series2);
options.series.push(series3);
options.series.push(series4);
options.series.push(series);
var chart = new Highcharts.Chart(options);
In the tool tip as of now it says "undefined".
It doesnt work, because you push only values into data array, but not define name of parametrs. You should push point as object, where you define name of your parameter and y value.
I have a highcharts bargraph whose values are received from json whose format is as follows:
"bargraph":
[
{
"categories": "['S', 'M', 'T', 'W', 'T', 'F']",
"series1": "[800, 1100, 80, 1800, 1600, 2000]",
"series2": "[800, 1100, 80, 1800, 1200, 800]"
}
]
How can i embed those values for my bargraph in angularJS
HTML Code:
<div id="bargraph" bargraph={{bargraph}}><\div>
Directive:
angular.module('example').directive('bargraph', function () {
element.highcharts({
xAxis: [
{
categories: [] //embed categories value here
},
series: [
{
name: 'series1',
data: [] //Embed series1 data here
},
{
name: 'series2',
data: [] //Embed series2 data here
}
]
})
})
Please provide a suitable way to embed the data from json.
Here is a directive i copied and pasted from my webapp it is how i render highcharts using a directive NOTE: not all of this directive is applicable to you and some of it is specific to what i needed but you get the idea.
lrApp.directive('chart', function () {
return {
restrict: 'E',
template: '<div></div>',
transclude: true,
replace: true,
link: function (scope, element, attrs) {
var chart = null;
var chartsDefaults = {
chart: {
renderTo: element[0],
type: attrs.type || null,
height: attrs.height || null,
width: attrs.width || null,
},
colors: scope.$eval(attrs.colors) || null,
title: {
style: {
display: 'none'
}
},
xAxis: {
//categories: ['{"-7 days"|date_format}','{"-6 days"|date_format}','{"-5 days"|date_format}','{"-4 days"|date_format}', '{"-3 days"|date_format}', '{"-2 days"|date_format}', '{"-1 day"|date_format}', '{$smarty.now|date_format}'],
categories: scope.$eval(attrs.dates) || null,
gridLineDashStyle: 'ShortDot',
gridLineColor: "#C0C0C0",
gridLineWidth: 1,
labels: {
y: 27
}
},
yAxis: {
title: {
text: null
},
min: 0,
gridLineDashStyle: 'ShortDot',
gridLineColor: "#C0C0C0",
gridLineWidth: 1
},
credits: {
enabled: false
},
legend: {
enabled: false
},
plotOptions: {
series: {
shadow: false,
lineWidth: 3
}
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
this.x + ': ' + this.y + '</b>';
}
}
};
//Update when charts data changes
scope.$watch(attrs.value, function (newVal, oldVal) {
if (!newVal.length) return;
// We need deep copy in order to NOT override original chart object.
// This allows us to override chart data member and still the keep
// our original renderTo will be the same
var deepCopy = true;
var newSettings = {};
chartsDefaults.series = newVal;
chartsDefaults.colors = scope.$eval(attrs.colors);
chartsDefaults.xAxis.categories = scope.$eval(attrs.dates);
console.log(chartsDefaults);
chart = new Highcharts.Chart(chartsDefaults);
});
}
}
});
and this is how it used it obviously you would change "line" to bar:
<chart value="stats.sets" dates="stats.days" colors="stats.colors" type="line"></chart>
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.