I m trying to figure it out that is it possible to make the json data fetched dynamically from a database with the help of php and mysql and can be plotted with highcharts that too dynamic auto updating? Any help would be appreciated.
following the code i have tried and is not working properly and want to implement to the the website for 10 lines.
<HTML>
<HEAD>
<TITLE>highchart example</TITLE>
<script type="text/javascript"src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script type="text/javascript">
var chart;
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is
// longer than 2
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData1, 1000);
},
cache: false,
});
}
function requestData1() {
$.ajax({
url: 'live-server-data.php',
success: function(point) {
var series2 = chart.series[1],
shift = series2.data.length > 20; // shift if the series is
// longer than 20
// add the point
chart.series[1].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false,
});
}
$(function () {
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis:
{
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: '',
margin: 80
}
},
series: [
{
name: 'Random data',
data: []
},
{
name: ' hahaha',
data: []
}
],
});
});
});
</script>
</HEAD>
<BODY>
<div id="container"
style="min-width: 728px; height: 400px; margin: 0 auto"></div>
</BODY>
</HTML>
*** the live-server-data.php is as followed:
<?php
// Set the JSON header
header("Content-type: text/json");
// The x value is the current JavaScript time, which is the Unix time multiplied
// by 1000.
$x = time() * 1000;
// The y value is a random number
$y = rand(48,52);
// Create a PHP array and echo it as JSON
$ret = array($x, $y);
echo json_encode($ret);
?>
You can try with
var options = {
chart: {
renderTo: 'chart',
},
credits: {
enabled: false
},
title: {
text: 'Impression/Click Overview',
x: -20
},
xAxis: {
categories: [{}]
},
tooltip: {
formatter: function() {
var s = '<b>'+ this.x +'</b>';
$.each(this.points, function(i, point) {
s += '<br/>'+point.series.name+': '+point.y;
});
return s;
},
shared: true
},
series: [{},{}]
};
$.ajax({
url: "json.php",
data: 'show=impression',
type:'post',
dataType: "json",
success: function(data){
options.xAxis.categories = data.categories;
options.series[0].name = 'Impression';
options.series[0].data = data.impression;
options.series[1].name = 'Click';
options.series[1].data = data.clicks;
var chart = new Highcharts.Chart(options);
}
});
The highcharts website has some useful articles about working with dynamic data. That is probably the best place to start.
http://www.highcharts.com/docs/working-with-data/preprocessing-live-data
http://www.highcharts.com/docs/working-with-data/preprocessing-data-from-a-database
Try something out, and if you have trouble, come back here with a more specific question showing what you have tried. As it stands, your question is too broad, and will probably get closed.
An ajax request for updating data looks something like:
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is // longer than 20
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
Related
i Have created a Highchart using the Following Highchart's Demo:
https://www.highcharts.com/demo/dynamic-update
Now What I did I created my Own function to add dynamic values to the Chart.
I created a function to get the dynamic data from a particular php file whose data changes on every page load event.
I am getting the data values in the getData function console.log
Here is the Script That I am using.
<script type="text/javascript">
$(document).ready(function(){
function getData(){
$.ajax({
type: 'GET',
url: 'data.php',
success: function(data){
// var number = document.write(data) ;
console.log(data);
return data ;
}
}) ;
}
Highcharts.chart('chart', {
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
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 = getData();
console.log(y);
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
time: {
useUTC: false
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
headerFormat: '<b>{series.name}</b><br/>',
pointFormat: '{point.x:%Y-%m-%d %H:%M:%S}<br/>{point.y:.2f}'
},
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 += 1) {
data.push({
x: time + i * 1000,
y: getData()
});
}
return data;
}())
}]
});
});
</script>
Now as you can see that I have created a getData function and getting the data value in return.
On console log under the getData function, I am getting integer Value in return every one second.
the problem is that under the Highchart's function, I am not able to get the data values using getData function, it's returning undefined in the console .
Highchart's is running but it does not show any data points. it is moving but without showing any data points.
Please correct me in the area , where I am doing wrong.
Any help is appreciated. Thanks
ajax calls are run asynchronously so you cant really return data from it.
instead you should render chart inside the ajax success function.
A good example is here already.
https://www.highcharts.com/docs/working-with-data/live-data
Basically
1. point on load to call a function getData
2. in Getdata call ajax function.
3. in success of ajax render chart with new data.
document.addEventListener('DOMContentLoaded', function() {
chart = Highcharts.chart('container', {
chart: {
type: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: [{
name: 'Random data',
data: []
}]
});
});
/**
* Request data from the server, add it to the graph and set a timeout
* to request again
*/
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is
// longer than 20
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second - add this if you want to auto refresh
// setTimeout(requestData, 1000);
},
cache: false
});
}
I've a question about how to create a dynamic chart using json, I tried and my graph didn't show a result, when I checked out, I've no error with my code. This is my code :
<script>
var chart; // global
function requestData() {
$.ajax({
url: 'api_heartrate.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // 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, 1000);
},
cache: false
});
}
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: [{
name: 'Random data',
data: []
}]
});
});
</script>
</head>
<body>
<div id="container" style="width: 800px; height: 400px; margin: 0 auto"></div>`
this is my json :
http://health.barrukurniawan.tech/api_heartrate.php
[{"time":"2018-08-02 09:30:11","nilai_sensor":"78"}]
I tried following a tutorial from this link :
Highcharts Dynamic Chart with MySQL Data doesn't reload
Thanks for your attention, gladly waiting for an answer :)
There are multiple small errors in your approach
eval is bad, parse it using JSON.parse instead.
During load, chart is not defined yet, so your callback will not work.
Highcharts needs time in milliseconds since 1970.
highcharts expects an object {x: , y: ,...} you give it {time: , nilai_sensor: }.
Solutions:
point = JSON.parse(point)
events: {
load: function() {
setInterval(function() {
requestData(chart)
}, 1000);
}
}
new Date(point[0].time).getTime()
{x: new Date(point[0].time).getTime(), y: point[0].nilai_sensor}
Here is a working example using your input with static data(and some added time to keep it moving): https://jsfiddle.net/ewolden/md975oLk/23/
Im fairly new to js and php , I am trying to load a live chart with mutliple series of btc price from exchanges from php files. Ive tried and failed, i can only get 1 of the data series to load , they all work individually but getting all of them to load as seperate points on the chart at the same time eludes me.
BITSTAMP.PHP -- results: [1519417809000,9932.83]
<?php
header("Content-type: text/json");
function bitstampbtcusdgetprice($url)
{ $decode = file_get_contents($url);
return json_decode($decode, true); }
$x = time() * 1000;
$y =
$btcusdgetprice('https://www.bitstamp.net/api/v2/ticker/btcusd');
$btcusdtickerprice = round(($y["last"]), 2);
$ret = array($x, $btcusdtickerprice);
echo json_encode($ret);
?>
CHART.JS
var chart;
function requestDatabitstamp() {
$.ajax({
url: 'php/bitstamp.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 100;
chart.series[0].addPoint(point, true, shift);
setTimeout(requestDatabitstamp, 30000);
},
cache: false
});
}
$(document).ready(function() {
chart = new
Highcharts.Chart({
colorAxis:{ gridlineColor: '#4c4c4c'},
marker:{ animation: '10000'},
chart:{ renderTo: 'container',
defaultSeriesType: 'line',
backgroundColor: '#141414',
borderColor: '#00A578',
plotbackgroundColor: '#161616',
parallelAxes: {linecolor: '#4c4c4c'},
events: { load: requestDatabitstamp}},
tooltip:{ style: {color: '#FFFFFF',
fontSize: '10px'},
backgroundColor: '#141414',
borderRadius: '12'},
title:{ text: '<font style="color:#FFFFFF;font-family:verdana;">Exchange Comparison</font>'},
plotOptions:{ series: {
color: '#00A578'}},
xAxis:{ type: 'datetime',
tickPixelInterval: 150,
maxZoom: 50 * 1000},
yAxis:{ minPadding: 0.2,
maxPadding: 0.2,
title:{ text: '<font style="color:#00A578;font-family:verdana;">USD</font>',
margin: 30}},
series: [{ color: '#00A578',
name: '<font align="center" style="color:#00A578;font-family:verdana;">Bitstamp</font>',
data: []
}]});});
I'm no expert with Highcharts but what I see is that you are filling only chart.series[0] with points so only one series is printed. You have to have series for each exchange.
Update:
Try creating an array filled with the data for each exchange in the PHP file and receiving it through AJAX, then create points for chart.series[1] and chart.series[2].
got it , heres the updated code. i had the other series i tried importing in the wrong places.
function requestData() {
$.ajax({
url: 'php/binance.php',
success: function(point) {
var series = chart.series[0],
shift0 = series.data.length > 50; // shift if the series is
// longer than 20
// add the point
chart.series[0].addPoint(point, true, shift0);
// call it again after one second
},
cache: false
});
$.ajax({
url: 'php/bitstamp.php',
success: function(point) {
var series = chart.series[1],
shift1 = series.data.length > 50; // shift if the series is
// longer than 20
// add the point
chart.series[1].addPoint(point, true, shift1);
// call it again after one second
},
cache: false
});
$.ajax({
url: 'php/bittrex.php',
success: function(point) {
var series = chart.series[2],
shift2 = series.data.length > 50; // shift if the series is
// longer than 20
// add the point
chart.series[2].addPoint(point, true, shift2);
// call it again after one second
setTimeout(requestData, 10000);
},
cache: false
});
}
I am loading Highcharts like this.
var options = {
credits: {
enabled: false
},
chart: {
renderTo: 'chart_box',
type: 'areaspline'
},
title: {
text: ''
},
xAxis: {
crosshairs: true,
labels: {
step: 5,
rotation: -45
}
},
series: []
};
Then I have a function which is called when graph needs to be loaded. Upon calling the function, data is fetched through AJAX and assigned to series and date lie this:
$.ajax({
url: 'url/charts',
type: 'post',
data: data
}).done(function(data) {
var dateCount = data.dates.length;
var stepCount = 1;
if (dateCount > 10) {
stepCount = 5;
}
options.xAxis.categories = data.dates;
$.each(data.series, function(name, elem) {
options.series.push({
name: name.replace('_', ' ').toUpperCase().trim(),
data: elem
})
});
chart = new Highcharts.Chart(options);
});
The issue here is that even though I have given step as 5 , it is showing dates with 15 dates interval. I mean in xAxis labels. It seems like it will be multiplied by three always. If I give 2, it will show 6 days interval in labels. Everything working fine in a chart which is not using AJAX to load data.
I'm trying to plot data from a mysql table on document load with highcharts:
the html looks like that:
function FetchData(){
//alert("Fetching");
$.ajax({
url: 'php/reports/fetch_data.php',
success: function(data) {
dataTemp = [];
for(i=0;i<data.length;i++){
dataTemp.push(data[i][0]); // '1' index for getting that temp value. '0' for date.
}
c_temperature.series[0].data = dataTemp;
for(i=0;i<data.length;i++){
dataTemp.push(data[i][1]); // '1' index for getting that temp value. '0' for date.
}
c_temperature.series[1].data = dataTemp;
}
});
function DrawCharts(){
c_temperature = new Highcharts.Chart({
chart: {
renderTo: 'dashboard',
defaultSeriesType: 'spline',
},
title: {
text: 'Temperatur'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 10
}
},
legend:{
enabled: false
},
credits:{
enabled: false
},
series: [{
name: 'Temperatur',
data: []
}]
});
$(document).ready(function() {
DrawCharts();
FetchDevices();
FetchData();
});
<body>
<div id="dashboard">
</div>
<div class="clear"></div>
</body>
And the php I call looks like that:
try {
$con = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);#
echo 'Connected</br>';
$sql = "select ZEIT,FEUCHTE,TEMPERATUR,LUX,PITCH from ".$mac.
" order by ID";
foreach($con - > query($sql) as $row) {
$x = $row['ZEIT'];
/*$x = mktime()*1000;*/
$y_h = (float) $row['FEUCHTE'];
/*$y_t=(float)$row['TEMPERATUR'];
$y_l=(float)$row['LUX'];
$y_a=(float)$row['PITCH'];*/
$ret = array($x, $y_h, /*$y_t,$y_l,$y_a,$mac*/ );
echo json_encode($ret);
}
$con = null;
}
The php code successfully returns data.
But I dont see a graph and debugging with the browser console does not give a clue either. Any suggestions what I'm doing wrong?
Beste Regards
You want to use c_temperature.series[0].setData(dataTemp, true); and c_temperature.series[1].setData(dataTemp, true);. By setting the data, you're not actually telling highcharts to redraw the chart, so nothing is happening when you update the data.
I think it has to do with the order in wich you do your operations: firstly you create the chart and then you make the ajax call to fetch the data, but you are not updating the chart.
Try to move the chart creation inside the ajax success callback: first populate the series array with the data received from PHP, then construct the chart passing the serie array as a option; like this:
success: function(data) {
var data_series = [];
/* here populate the data_series array from your PHP results */
new Highcharts.Chart({
/* here other options... */
series: data_series
});
So this is what I'm doing now:
function FetchData(){
$.ajax({
type: "POST",
url: 'php/reports/fetch_data.php',
data: "",
dataType: 'json',
success: function(data) {
var points = data;
c_temperature = new Highcharts.Chart({
chart: {
renderTo: 'dashboard',
defaultSeriesType: 'spline',
},
title: {
text: 'Temperatur'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: '°C',
margin: 10
}
},
legend:{
enabled: false
},
credits:{
enabled: false
},
series: points
});
/*dataTemp = [];
for(i=0;i<data.length;i++){
dataTemp.push(data[0][i]);
}
c_temperature.series[0].setData(dataTemp, true);
for(i=0;i<data.length;i++){
dataTemp.push(data[1][i]);
}
c_temperature.series[1].setData(dataTemp, true);*/
}
});
}
Result: it is showing the graph but still no plot.
The php return has been changed to this:
try {
$con = new PDO("mysql:host=$servername; dbname=$dbname" ,$username, $password);
$sql = "select ZEIT,FEUCHTE,TEMPERATUR,LUX,PITCH from ".$mac." where ID>'60080' order by ID";
$x = array();
$y_h = array();
foreach ($con->query($sql) as $row)
{
$x[]=$row['ZEIT'];
$y_h[]=(float)$row['FEUCHTE'];
$ret = array($x,$y_h);
}
echo json_encode($ret);
$con = null;
}