Related
I'm trying to create a highchart with irregular x axis, a bit like this: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/spline-irregular-time/
I'm pulling my data from mySQL via PHP and processing in JSON format.
I can't get highcharts/JS to read the dates in date format - it seems to be pulling them as strings.
Here's my script:
$(document).ready(function() {
var options = {
chart: {
type: 'spline',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'some title',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: { // don't display the dummy year
month: '%e. %b',
year: '%b'
},
categories: []
},
yAxis: {
title: {
text: 'L/min'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
plotOptions: {
spline: {
marker: {
enabled: true
}
}
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +': '+
this.y +'</b><br>'+ this.x;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
}
$.getJSON("allreports/report.php", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
options.chart.renderTo = 'container';
chart = new Highcharts.Chart(options);
});
and here's my PHP page:
<?php
$con = mysql_connect("localhost","db-user","db-pw");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$sth = mysql_query("SELECT v1,v2 FROM table");
$rows = array();
$rows['name'] = 'v1';
while($r = mysql_fetch_array($sth)) {
$rows['data'][] = $r['v1'];
}
$result = array();
array_push($result,$rows1);
array_push($result,$rows);
print json_encode($result, JSON_NUMERIC_CHECK);
mysql_close($con);
?>
This outputs the following:
[{"name":"medicinetime","data":["01,01,1970,01,00,00","01,01,1970,01,33,36","01,01,1970,01,33,36","01,01,1970,01,33,36"]},{"name":"units","data":[1,3,2,2]}]
But my chart is as follows:
Any thoughts on what I'm doing wrong please? What do I need to do to get PHP/JS to pick up on this array as a series of datetimes rather than strings?
Thank you!
You have two issues. First, you need to convert your date-component values into an actual Javascript date object. The format you're looking for for your series data is an array of X/Y pairs. It'll look like this, using your data:
[
[Date.UTC(1970,1,1,1,0,0),1],
[Date.UTC(1970,1,1,1,33,36),3],
[Date.UTC(1970,1,1,1,33,36),2],
[Date.UTC(1970,1,1,1,33,26),2]
]
Try something like this:
var xVals= json[0].data.map( item => {
var dateArr = point[0].join(',');
return Date.UTC(dateArr[2],dateArr[1],dateArr[0],dateArr[3],dateArr[4],dateArr[5]);
});
var yVals = json[1].data;
options.series[0] = {
name: json[1].name,
data: xVals.map( (x,i) => [x,yVals[i]])
}
Some documentation on valid formats for the series data is here: http://www.highcharts.com/docs/chart-concepts/series
Second, you have some duplicate X values there, and that's going to be confusing...you're going to want your timestamps to be unique, or it's going to be hard to make a line chart out of them.
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;
}
How can I introduce in the highcharts code an array that comes from a php code?
In the next code php I generate 4 arrays, 3 for Data (TMax ($rows), TMin ($rows1) and Rain ($rows2) and the last one for the days of the consulting ($dia).
$sth = mysqli_query($con,"SELECT City,TMax, Day(Date) As Dia FROM Meteo2 where City= '" . $_SESSION["City"] ."' AND Data BETWEEN '" . split($_SESSION["date8"]) ."' AND '" . split($_SESSION["date9"]) ."'order by Date");
$rows = array();
$dia = array();
$dia['name'] = 'Dia';
$rows['name'] = 'TMAX';
$rows['color'] = '#FF0000';
$cont=1;
while($r = mysqli_fetch_array($sth)) {
$rows['data'][] = $r['TMax'];
$dia['categories'][] = $r['Dia'];
}
$sth = mysqli_query($con,"SELECT City,TMin FROM Meteo2 where City= '" . $_SESSION["City"] ."' AND Data BETWEEN '" . split($_SESSION["date8"]) ."' AND '" . split($_SESSION["date9"]) ."'order by Date");
$rows1 = array();
$rows1['name'] = 'TMIN';
$rows1['color'] = '#00FFFF';
$rows1['var valueSuffix'] = 'ºC';
while($rr = mysqli_fetch_assoc($sth)) {
$rows1['data'][] = $rr['TMin'];
}
mysqli_query($con,"SELECT City,Rain FROM Meteo2 where City= '" . $_SESSION["City"] ."' AND Data BETWEEN '" . split($_SESSION["date8"]) ."' AND '" . split($_SESSION["date9"]) ."'order by Date");
$rows2 = array();
$rows2['name'] = 'RAIN';
$rows2['type'] = 'column';
$rows2['color'] = '#4572A7';
$rows2['var valueSuffix'] = 'mm';
$rows2['var yAxis'] = 2;
while($rr = mysqli_fetch_assoc($sth)) {
$rows2['data'][] = $rr['Rain'];
}
$result = array();
array_push($result,$rows2);
array_push($result,$rows1);
array_push($result,$rows);
array_push($result,$dia);
print json_encode($result, JSON_NUMERIC_CHECK);
mysqli_close($con);
?>
When I plot the chart, I can see the line of rain, TMax, TMin, but in the Xaxis by default I have 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15....and what I need is the information of $dia inside categories[]
and when i check the browser I see categories empty...
xAxis: {
categories: []
},
but in the highchart code I have
xAxis: {
categories: ['<?php echo $dia?>']
},
any help please????
Here I show the highcharts code
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>www.meteo4u.com/consultaNouformat.html</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script type="text/javascript">
<?php
$city = $_POST["City"];
session_start();
$_SESSION['City'] = $_POST['City'];
$_SESSION['date8'] = $_POST['date8'];
$_SESSION['date9'] = $_POST['date9'];
?>
$(function () {
var chart;
$(document).ready(function() {
$.getJSON("mysql-highcharts.php", function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'spline',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Temperatura Maxima, Temperatura Minima i Precipitacio a <?php echo $city ?>',
x: -20 //center
},
xAxis: {
categories: [<?php echo $dia?>]
},
yAxis: [{
labels: {
format: '{value}°C',
style: {
color: '#FF0000'
}
},
title: {
text: 'Temperatura Maxima',
style: {
color: '#FF0000'
}
}
},{title: {
text: 'Temperatura Minima',
style: {
color: '#00FFFF'
}
}
},{labels: {
format: '{value} mm',
style: {
color: '#4572A7'
}
},
title: {
text: 'Precipitacio',
style: {
color: '#4572A7'
}
},opposite: true
}],
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
credits:{
text: 'meteo4u.com',
href:'http://meteo4u.com',
itemStyle: {
fontSize: '40px'
}
},
series: json
});
});
});
});
</script>
</head>
<body>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
It looks like $dia is an array is an array, containing an entry called 'categories'. I don't think you can somply echo the array variable in your highcharts code, as dia only exists in php on the server. You are returning the categories inside your json object in the 3rd entry of the array
array_push($result,$dia);
This means you have to read the categories out of the returned json in your highcharts code. Your code is hard to follow, but try this:
xAxis: {
categories: json[3]['categories'];
},
However, I am worried about this line:
series: json
The returned json does not just contain series definitions as it contains the categories as well. It may work, but is not very clean code.
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
Good evening everyone,
this moment I try to work with HighChart / HighStock and after several weeks I were able to display my MySQL-data in the charts. But: I always want more.
Well, I try to reach a dynamic chart which is refreshing like the examples you may know from the website. http://jsfiddle.net/sdorzak/HsWF2/
I used the sample code as a guide. It doesn't work, but think the problem is the missing y-axis because y-axis data come from my MySQL database while x-axis should be the current time.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>POS RESULT</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
</head>
<body>
<?php
include "config.php";
$SQL1 = "SELECT * FROM Prices WHERE ticker ='FB'";
$result1 = mysql_query($SQL1);
$data1 = array();
while ($row = mysql_fetch_array($result1)) {
$data1[] = $row['Close'];
}
?>
<script type="text/javascript">
$(function () {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 25,
events: {
load: function()
{
var series = this.series[0];
setInterval(function() {
var x = (new Date()).getTime();
series.addPoint([x], true);
}, 1000);
},
title: {
text: 'Monthly Average Temperature',
x: -20 //center
},
subtitle: {
text: 'Source: WorldClimate.com',
x: -20
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
//categories: [<?php echo join(',', $data2); ?>],
},
yAxis: {
title: {
text: 'Temperature (°C)'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y +'°C';
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: [{
name: 'Tokyo',
data: [<?php echo join(',', $data1); ?>]
}]
});
});
});
</script>
<div id="container" style="min-width: 500px; height: 400px; margin: 0 auto"></div>
</body>
</html>
The passage I am talking about and which is shown in the samples is
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);
}
}
But, as I already wrote, I don't need a random y-axis, just x-axis.
Maybe you can help.
Thanks for your help.
Edit:
live-server-data.php
<?php
// Set the JSON header
header("Content-type: text/json");
include "config.php";
$SQL1 = "SELECT * FROM Prices WHERE Ticker ='TSLA'";
$result1 = mysql_query($SQL1);
while ($row = mysql_fetch_array($result1)) {
$data1[] = $row['Close'];
}
// 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 = $data1;
// Create a PHP array and echo it as JSON
$ret = array($x, $y);
echo json_encode($ret);
?>
The value "Close" is decimal 24,4.
See that solution: http://www.highcharts.com/studies/live-server.htm
var chart; // global
/**
* 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(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: []
}]
});
});
im trying to create another page that can relate to my bar chart. You can go through his code. It work for me
<!DOCTYPE html>
<html>
<head>
<?php
session_start();
?>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script>
$('#calendar').datepicker({
});
!function ($) {
$(document).on("click","ul.nav li.parent > a > span.icon", function(){
$(this).find('em:first').toggleClass("glyphicon-minus");
});
$(".sidebar span.icon").find('em:first').addClass("glyphicon-plus");
}(window.jQuery);
$(window).on('resize', function () {
if ($(window).width() > 768) $('#sidebar-collapse').collapse('show')
})
$(window).on('resize', function () {
if ($(window).width() <= 767) $('#sidebar-collapse').collapse('hide')
})
</script>
<style>
.selection{
border: 1px solid gray;
border-radius: 10px;
padding: 10px;
text-decoration:none;
float:left;
margin:4px;
text-align:center;
display: block;
color: green;
}
.page-header{
text-align:center;
text-decoration:hover;
color: blue;
font-size: 30px;
}
</style>
<script>
$(function () {
//on page load
getAjaxData(1);
//on changing select option
$('#dynamic_data').change(function(){
var val = $('#dynamic_data').val();
getAjaxData(val);
});
function getAjaxData(id){
//use getJSON to get the dynamic data via AJAX call
$.getJSON('datab1.php', {id: id}, function(chartData) {
$('#container').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Analysis of Data Type in The World'
},
xAxis: {
categories: ['Population', 'Health', 'Agriculture', 'Development', 'Transport', 'Education', 'Social', 'Tourism', 'Finance','Business','Economy', 'Industry', 'Employment', 'Weather', 'Food', 'Energy', 'Infrastructure', 'Science&Technology', 'Government','Culture', 'Religion',
'Justice&Law', 'Country', 'Water Resource', 'Maritim', 'Military', 'International', 'Geography', 'Statistics', 'Others','Electronic','Biotechnology', 'Women', 'Gender', 'Cartography','Disability','Position','Marital','CDF','Research']
},
yAxis: {
min: 0,
title: {
text: 'Percentage (%)'
}
},
legend: {
enabled: false
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} %</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: chartData
});
});
}
});
</script>
</head>
<body class="hold-transition skin-blue sidebar-mini">
<div id="container" style="width: 100%; min-height: 500px; margin: 0 auto"></div>
</body>
</html>
And this the code for fetching data from mysql
<?php
require('dbcon.php');
//select database
//define array
//we need two arrays - "male" and "female" so $arr and $arr1 respectively!
$arr = array();
$result = array();
//get the result from the table "highcharts_data"
$sql = "select * from world";
$q = mysqli_query($con, $sql) or die(mysqli_error());
$j = 0;
while ($row = mysqli_fetch_assoc($q)) {
//highcharts needs name, but only once, so give a IF condition
if ($j == 0) {
$arr['name'] = 'Percentage';
$j++;
}
//and the data for male and female is here
$arr['data'][] = $row['datavalue'];
}
//after get the data for male and female, push both of them to an another array called result
array_push($result, $arr); //1
//now create the json result using "json_encode"
print json_encode($result, JSON_NUMERIC_CHECK);
mysqli_close($con);
?>