Drawing mysql data with highcharts - javascript

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;
}

Related

Made dynamic highstock with PHP data

I made a dynamic highstock (highchart) like this example, but with data from PHP. I have tried my code, but the results did not appear. How to make dynamic highstock with PHP?
PHP code :
<?php
include("connection.php");
$data = array();
$count = 0;
$result = mysqli_query($koneksi,"SELECT * FROM data ORDER BY time ASC ") or die ("Connection error");
while($row = mysqli_fetch_array($result)) {
$x = strtotime($row['time']) * 1000;
$y = (float)$row['temperature'];
$data[] = array($x, $y);
$count++;
}
echo json_encode($data);
mysqli_close($koneksi);
?>
JSON from PHP:
[[1535981121000,40],[1535981432000,32.9],[1535981492000,32.7],[1535981552000,32.6],[1535981618000,32.6],[1535981672000,32.6],[1535981732000,32.6],[1535981793000,32.6],[1535981854000,32.6],[1535981913000,32.5],[1535981993000,32.4],[1535982034000,32.4],[1535982215000,32.4],[1535982287000,32.3],[1535982335000,32.3],[1535982396000,32.5],[1536576266000,45.2],[1536579542000,62.2],[1536653234000,30.2]]
Javascript code:
<script type="text/javascript">
var chart;
function requestData() {
$.ajax({
url: 'chartTemp.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20;
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
document.addEventListener('DOMContentLoaded', function() {
chart = Highcharts.stockChart('container', {
chart: {
events: {
load: requestData
}
},
time: {
useUTC: false
},
rangeSelector: {
buttons: [{
count: 1,
type: 'minute',
text: '1M'
}, {
count: 5,
type: 'minute',
text: '5M'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: true,
selected: 0
},
title: {
text: 'Live random data'
},
exporting: {
enabled: true
},
series: [{
name: 'Random data',
data: data[]
}]
});
</script>
I changed the javascript code above from this example
You are missing either,
// Set the JSON header (in .php)
header("Content-type: text/json");
Or like,
$.ajax({
method: "GET",
url: "test.js",
dataType: "json"
});
Also you have some syntax errors, at the end of javascript code add below (to confirm check in browser's console window),
)};
Your ajax call is returning all of the points in a single json, but the function you are calling looks like don't accept, so check again,
// add the point
chart.series[0].addPoint(point, true, shift);

MYSQL Database to Highcharts graph via Ajax

I have a database with timestamp for three different parameters but for educational purposes only I am trying to do just one graph on one parameter in real time.
Here is my php code:
if ($result->num_rows > 0) {
$count =0;
echo '[';
while($row = $result->fetch_assoc()) {
echo '['.$row["time"].','.$row["temperature"].']';
$count++;
if ($count<"100") {
echo ',';
}
}
echo ']';
}
else {
echo "[[],[]]";
}
$link->close();
?>
The following php code displays:
[[1511533905000,34],[1511534125000,34],[1511534201000,34],[1511535161000,34],[1511535221000,34],[1511535281000,34],[1511535306000,34],[1511535606000,34],[1511535907000,34],[1511536207000,34],[1511536507000,34],[1511536807000,34],[1511537108000,34],[1511537408000,34],[1511537708000,34],[1511538070000,85],[1511538370000,31],[1511538670000,31],[1511538971000,30],[1511539271000,30],[1511539571000,30],[1511539872000,30],[1511540172000,30],[1511540472000,30],[1511540773000,30],[1511936414000,25],[1511936714000,24],[1511937014000,85],[1511937315000,24],[1511937616000,24],[1511937916000,24],[1511938216000,24],[1511938517000,24],[1511938817000,24],[1511939117000,24],[1511939417000,24],[1511939718000,24],[1511940018000,24],[1511950908000,85],[1511951208000,23],[1511951509000,23],[1511951809000,23],[1511952109000,23],[1511952410000,23],[1511952710000,22],[1511953010000,22],[1511953310000,22],[1511953611000,22],[1511953911000,22],[1511954211000,22],[1511954512000,22],[1511954812000,22],[1511955112000,22],[1511955412000,22],[1511955713000,22],[1512056186000,31],[1512056486000,85],[1512056787000,30],[1512057087000,31],[1512057387000,30],[1512057688000,30],[1512057988000,30],[1512058289000,30],[1512058589000,30],[1512058889000,30],[1512059189000,30],]
now here is the html code:
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
//defaultSeriesType: 'spline',
},
title: {
text: 'Live random data'
},
events:{
load: refreshChart()
},
xAxis: {
type: 'datetime',
},
tooltip: {
valueSuffix: ' C'
},
yAxis: {
type: 'linear',
title: {
text: 'Temperature ( C)'
},
},
series: [{}]
});
$.getJSON("index.php", function(json) { /*Get the array data in data.php using jquery getJSON function*/
options.series[0].data = json; /*assign the array variable to chart data object*/
chart = new Highcharts.Chart(options); /*create a new chart*/
});
function refreshChart(){ /*function is called every set interval to refresh(recreate the chart) with the new data from data.php*/
setInterval(function(){
$.getJSON("index.php", function(json) {
options.series[0].data = json;
chart = new Highcharts.Chart(options);
});
},6000);
}
});
But the graph doesnt display anything? Anyhelp pls?
SOLVED!! I just converted the output of my array in the index.php.
$output[] = array(((float)($row["time"])),((int)($row["temperature"])));
in this way both the timestamp and the value of the temperature are both valid json.

Highcharts dynamic graph with database value

I am working with Highchart. I want to draw dynamic graph with database value. I use json format.
Here is my json file:
<?php
// Set the JSON header
header("Content-type: text/json");
include"../veri_ayar.php";
$sql = "SELECT Guc FROM Urun ORDER BY KayitTarihi DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
$data = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
$x = time() * 1000;
foreach($data as $dat)
{
$date .= $dat['Guc'];
}
mysqli_close($conn);
$ret=array($x, $date);
echo json_encode($ret);
?>
And my output is : [1479814215000,"43"]
When I write to just $date for control it looks like: just 43 but when I write to json format it looks like "43".
When I want to draw graph my graph is shift left but no data in graph. just shift to left.
Here is my graph script:
<script>
var chart;
function requestData() {
$.ajax({
url: 'veri-json.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
});
}
$(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>

dynamic highcharts with json data

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
});
}

Highcharts using JSON - graph not displaying mysql data

I have been able to produce results from mysql using:
$myArray=array();
$tempArray = array();
// Get all records
while ( $row = $results->fetch_assoc())
{
$tempArray = $row;
array_push($myArray, $tempArray);
}
echo json_encode($myArray);
$mysqli->close();
?>
And I then included this to produce a chart on my page index.php by using the following Javascript.
what concepts/code am I not understanding/missing to produce a chart based upon my ajax json?
EDITED - SOLUTION:
Final PHP code to produce the json:
while ( $row = $results->fetch_assoc())
{
$tempArray[0] = $row['unix_timestamp(auct.end_date)'];
$tempArray[0] *= 1000;
$tempArray[1] = $row['winning_bid'];
array_push($myArray, $tempArray);
}
echo json_encode ($myArray, JSON_NUMERIC_CHECK);
$mysqli->close();
?>
Final javascript code:
$('#btn_search').click(function(){
txt_search = $('#txt_search').val();
$.ajax({
url: './php/search.php',
type: 'GET',
data: {search: txt_search},
dataType: 'json',
success: function(rows)
{
chart = new Highcharts.Chart({
chart: {
renderTo: 'chartdiv',
type: 'line',
marginRight: 100,
marginBottom: 50
},
title: {
text: 'Whisky Tracking',
x: -20 //center
},
xAxis: {
text: 'EndDate',
type: 'datetime'
},
yAxis: {
title: {
text: 'Price',
color: '#CC680E'
},
plotLines: [{
value: 0,
width: 20,
color: '#CC680E'
}]
},
series: [{
name: txt_search,
xAxis:0,
data: rows,
dataLabels: {
enabled: true,
formatter: function() {
return '£'+ Highcharts.numberFormat(this.y, 0);
}
}
}],
});
}
});
goToByScroll('tracker');
return false;
});
Sample Data from the JSON:
[1306732000000,160],[1306745000000,45],[1306788000000,65],[1306788000000,50],[1306712000000,130],[1306733000000,240],[1306744000000,60],[1306788000000,250],[1306710000000,145]
The problem is that values are strings, for example, your data:
["2011-05-30 00:00:00","130"]
Should be instead:
[1306706400000, 130]
To it's timestamp in ms and true value.
You can read about JSON_NUMERIC_CHECK option for json_encode(string, JSON_NUMERIC_CHECK) to change strings to numbers. But dates to timestamps you need to change on your own.
Edit:
Also the problem was with setting data in doubled array, changed from:
data: [rows]
to:
data: rows

Categories