Getting dynamic values from database for dynamic chart plotting - php

I want to retrieve values dynamically from the database and plot using Highcharts spline graph. The problem is I cant figure out a way to pass the values to Javascript function without refreshing the whole function, this will plot the whole graph from the scratch. The current code contains an array where it just plots using an array and a random function to generate new values. I want to find a way to insert new values on to that array from the database using PHP. Problem is I don't know how to keep on calling the database query without affecting the graph. Some help on plotting the graph dynamically using the dynamic values from the database would be helpful.
$(function () {
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart;
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'spline',
marginRight: 10,
events: {
load: function() {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function() {
var x = (new Date()).getTime(), // current time
y = Math.random();
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
title: {
text: 'Trend analysis'
},
xAxis: {
labels: {
rotation: 320
},
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
credits:{
enabled:false
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) +'<br/>'+
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Random data',
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i++) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
})()
}]
});
});
});

The technique you are looking for is called ajax. This is where the javascript requests more data from the server without the whole page loading. The basic approach is:
The page is loaded and renders the initial chart.
The page then requests additional data fromthe user. In jquery, this is done using a call to$.ajax
The server responds with some more data.
The javascript loads this data into the chart using chart.series.addpoint or chart.series.setData.
Steps 2 to 5 are then repeated at regular intervals.
Highcharts has good article on this here: http://docs.highcharts.com/#preprocessing-live-data with some example code. You will need to amend the php to read the data from your database, and you may want to change the shift logic in the javascript depending on whether you want old points to drop off, or stay on the chart.
If you series isn't too big, it's not unreasonable to return the whole data set each time and use chart.series.setData to replace the entire series, instead of doing it point by point. The API calls you need are documented here: http://api.highcharts.com/highcharts#Series

Related

flot chart loading from database

i have this code for bar chart but i want to load the data for mysql database
/*
* BAR CHART
* ---------
*/
var bar_data = {
data: [["20-30", 10], ["31-40", 8], ["41-50", 4], ["51-60", 13]],
color: "#3c8dbc"
};
$.plot("#bar-chart", [bar_data], {
grid: {
borderWidth: 1,
borderColor: "#f3f3f3",
tickColor: "#f3f3f3"
},
series: {
bars: {
show: true,
barWidth: 0.5,
align: "center"
}
},
xaxis: {
mode: "categories",
tickLength: 0
}
});
/* END BAR CHART */
There are some hacky ways of using json_encode to output a PHP array in between some <script> tags as one solution.
The better solution though is often to use AJAX to request the data back as JSON and initialize your graph from that. In this way, you are not creating global javascript data variables outside of your javascript.

Plotting data on a Flot Chart using angularjs and json using $http

I created an application using angularjs, php and mysql. I have set an RESTful API which exports the mysql data to json. I would like to know how to plot the "Copra_Mc" data alone on a flot line chart using the below JSON data.
[
{
"productionhourlyNumber": "94",
"Copra_Mc": "5.88741898",
"Copra_Oil": "0.64851388"
},
{
"productionhourlyNumber": "93",
"Copra_Mc": "6.88741898",
"Copra_Oil": ""
},
{
"productionhourlyNumber": "92",
"Copra_Mc": "5.89998",
"Copra_Oil": ""
}
]
HTML
<div class="tile-body" ng-controller="LineChartCtrl">
<flot dataset="dataset" options="options" height="250px"></flot>
</div>
JS
I have set dummy json in the controller, i would like fetch data from the above json using $http instead of the dummy data
.controller('LineChartCtrl', function ($scope) {
$scope.dataset = [{
data: [[1,20.3],[2,5.9],[3,7.2],[4,8],[5,7],[6,6.5],[7,6.2],[8,6.7],[9,7.2],[10,7],[11,6.8],[12,7]],
label: 'Copra_Mc',
points: {
show: true,
radius: 6
}
}, {
data: [[1,6.6],[2,7.4],[3,8.6],[4,9.4],[5,8.3],[6,7.9],[7,7.2],[8,7.7],[9,8.9],[10,8.4],[11,8],[12,8.3]],
label: 'OEE',
points: {
show: true,
radius: 6
}
}, {
data: [[1,9.6],[2,7.4],[3,8.6],[4,13.4],[5,8.3],[6,7.9],[7,14.2],[8,7.7],[9,8.9],[10,8.4],[11,8],[12,8.3]],
label: 'OVE',
points: {
show: true,
radius: 6
}
}];
}
};
})
The chart looks like this
You need to use flow chart directive to use json by $http
download directive for flot chart in angularjs here
https://www.npmjs.com/package/angular-flot
https://github.com/ErikAugust/angularjs-flot-chart-directive
and use similar to this
http://www.codeandyou.com/2015/02/injecting-service-to-directives-in.html

How to graph jqplot using datetime as yaxis and category for xaxis

var bar_fan = ['8:30','10:30'];
var bar_ticks = ['a','b'];
$(document).ready(function(){
plot2 = $.jqplot('bar_all', [bar_fan], {
seriesDefaults: {
renderer:$.jqplot.BarRenderer,
pointLabels: { show: true },
},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: bar_ticks,
},
},
legend: {
show: true,
labels: bar_labels,
placement: 'outside'
}
});
bar_fan = ['8:30','10:30']; wont work. cause its time format.
if use value like bar_fan = [1,2]; will work.
how can I use yaxis with datetime value?
I got his working simply by adding the following to the axes configuration:
yaxis: {
renderer: $.jqplot.DateAxisRenderer
}
Now because yours are just time values, the graph will assume the current date. You may then want to specify either a minimum date or explicitly supply both date and time information, e.g., '2013-03-01 8:30AM'

javascript php mysql flot database

everyone! I have issues with regard to my x-axis. I'm using the api of flot. In my case, I'm extracting data from mysql to plot the graph. Both axes requires data to be extracted from mysql. For example, mysql will extract a data for the Y axis, say 20. My x axis will extract data from mysql of that particular time.
I tried to rewrite the script a few times, but to no conclusion. I tried attempting to create a variable, options, but it didn't work. It works only if I place the x axis statement just below y. The whole idea of creating a new variable options because I wanted to do a loop for the x-axis to continouous collect data from mysql. In the below quote, I simulated it with selected arrays.
$(function () {
var graph = [];
var power = <?php echo json_encode($data);?>;
var time = <?php echo json_encode($times);?>;
var row = <?php echo json_encode($nrow);?>;
//alert(time.toSource());
for (var i = 1; i < row; i += 1) {
//var test = time[i];
//alert(test);
//graph.push([i, power[i]]);
var hhmm = time[i].split(":");
var hh = parseInt(hhmm[0]);
var mm = parseInt(hhmm[1])/60;
var tt = hh+mm;
//var tx = hh;
graph.push([tt, power[i]]);
}
var options = {
xaxis: { ticks:[[1,time[1]],[2,time[2]],[3,time[3]],[4,time[4]],[5,time[5]],[6,time[6]],[7,time[7]],[8,time[8]]]}
};
//alert(options.toSource());
var plot = $.plot($("#placeholder"),
[ { data: graph, label: "Power" } ], {
series: {
lines: { show: true },
points: { show: true }
},
grid: { hoverable: true, clickable: true },
yaxis: { min: 0, max: 25 },
//xaxes: [ { mode: 'time' } ]
//xaxis: { mode: "time"}
//xaxis: { mode: "time",timeformat:"%H/%M" }
//xaxis: { ticks:[[1,time[1]],[2,time[2]],[3,time[3]],[4,time[4]],[5,time[5]],[6,time[6]],[7,time[7]]]}
}), options);
I have changed the options function, but it doesn't work.
var options = {
series: {
lines: { show: true },
points: { show: true }
},
grid: { hoverable: true, clickable: true },
yaxis: { min: 0, max: 25 },
for (var i = 1; i < row; i += 1)
{
xaxis: { ticks:[[i,time[i]]}
};
};
If I've surmised the format you wish for xaxis correctly, you could try the following:
var ticks = [];
for (var i = 1; i < row; i += 1)
{
ticks.push ([i, time[i]]);
}
var xaxis = {
ticks: ticks,
// ... any additional properties...
};
This will create an object xaxis with the property ticks which in turn is an array of arrays where each sub-array has two elements, the counter starting with one and the value of the time array for each i. I suppose you'll want to use code similar to this to create options:
var options = {
series: { lines: { show: true },
points: { show: true } },
grid: { hoverable: true, clickable: true },
yaxis: { min: 0, max: 25 },
xaxis: xaxis
};
You cannot use the for() statement in the object initialization, you'll have to create the xaxis array before, and use the variable name when creating the options object.

javascript php mysql flot

I encountered a new problem regarding my x-axis. My intention was to output a x-axis which indicates the time, while the y axis indicates the power. I decided to use time[i] and using graph.push([time[i], power[i]). However,my graph remains empty. I did an alert to output function and this was the result I got:
({1:"14:36", 2:"14:39", 3:"14:42", 4:"14:45", 5:"14:48", 6:"14:51", 7:"14:54", 8:"14:57"})
It's in hour: mins. What should I change to obtain a time X-axis?
$(function () {
var graph = [];
var power = <?php echo json_encode($data);?>;
var time = <?php echo json_encode($times);?>;
var row = <?php echo json_encode($nrow);?>;
//alert(time.toSource());
for (var i = 1; i < row; i += 1) {
//var test = time[i];
//alert(test);
graph.push([time[i], power[i]]);
}
var plot = $.plot($("#placeholder"),
[ { data: graph, label: "Power" } ], {
series: {
lines: { show: true },
points: { show: true }
},
grid: { hoverable: true, clickable: true },
yaxis: { min: 0, max: 25 }
});
You have to convert time from hour:mins to number
for (var i = 1; i < row; i += 1) {
//var test = time[i];
//alert(test);
var hhmm = time[i].split(":");
var hh = parseInt(hhmm[0]);
var mm = parseInt(hhmm[1])/60;
var tt = hh + mm;
graph.push([tt, power[i]]);
}
EDIT ( Eugene Wong) :
//var options = {
// xaxis: { ticks:[[1,time[1]],[2,time[2]],[3,time[3]],[4,time[4]],[5,time[5]],[6,time[6]],[7,time[7]],[8,time[8]]]}
//};
//alert(options.toSource());
var plot = $.plot($("#placeholder"),
[ { data: graph, label: "Power" } ], {
series: {
lines: { show: true },
points: { show: true }
},
grid: { hoverable: true, clickable: true },
yaxis: { min: 0, max: 25 },
xaxis: { mode: "time", timeformat:"%hh:%mm" }
//xaxis: { ticks:[[1,time[1]],[2,time[2]],[3,time[3]],[4,time[4]],[5,time[5]],[6,time[6]],[7,time[7]],[8,time[8]]]}
});
EDIT(Diode):
Even though I have created time charts before, this time setting x-axis configuration didn't work. Anyway I have fixed this by adding a tick formatter function. See the code below. 'graph' is the sample data array I used.
var graph = [[14.5, 10], [16.45, 15], [18.45, 20]];
var plot = $.plot($("#placeholder"),
[ { data: graph, label: "Power" } ], {
series: {
lines: { show: true },
points: { show: true }
},
grid: { hoverable: true, clickable: true },
yaxis: { min: 0, max: 25 },
xaxis: {
min:14,
max:20,
tickSize:0.5,
tickFormatter: function(value){
var hours = Math.floor(value);
hours = (hours < 10)?"0"+hours:hours;
var minutes = (value - hours) * 60;
minutes = (minutes < 10)?"0"+minutes:minutes;
return hours + ":" + minutes;
}
}
});
Have PHP output a Javascript timestamp instead of the already formatted date/time. Just remember a few caveats about timestamps:
PHP timestamps are seconds, whereas javascript ones are milliseconds, so multiply by 1000
flot plots in UTC time, so you may need to convert your timestamp to UTC before outputting
There is a good example of time series data on the flot website.
Remember to specify xaxis: { mode: "time" } in your flot options.

Categories