MSSQL Server to PHP Array to JSON Encode to Highcharts - javascript

I have very simple data that has come from my MSSQL Server to a JSON_Encode.
Here is my PHP Code (located in myPHPFile.php):
<?php
$serverName = "MyServer";
$connectionInfo = array( "Database"=>"MyDatabase", "UID"=>"MyUID", "PWD"=>"MyPWD");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$tsql = "SELECT * FROM [MyDatabase].[dbo].[MyView] ORDER BY Year";
$stmt = sqlsrv_query( $conn, $tsql);
$rows = array();
while($r = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$res[] = $r;
}
print json_encode($res, JSON_NUMERIC_CHECK);
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);
?>
That gives me the following print:
[{"Year":2016,"Number":41},{"Year":2017,"Number":512},{"Year":2018,"Number":1895},{"Year":2019,"Number":3132}]
Great. There's the data.
I've tried every tutorial, every highcharts forum post, and every stackoverflow question to get this simple data from my php file in JSON format, into a Highcharts Chart. Perhaps I am missing something obvious.
So let's look at my HTML file:
In the head:
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script type="text/javascript">
$(function () {
var chart;
$(document).ready(function() {
$.getJSON("myPHPFile.php", function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
},
xAxis: {
title: { text: 'Year'}
},
yAxis: {
title: {
text: 'Number'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
series: json
});
});
});
});
</script>
And then obviously my div
<div id="container"></div>
What am I missing? The HTML window is just blank. No chart rendered.

The Highchart examples show another example to setup the chart. The following format can be used:
$(document).ready(function() {
$.getJSON("myPHPFile.php", function(json) {
var series = json.map(function(record){
return [record.Year, record.Number];
})
Highcharts.chart('container', {
chart: {
renderTo: 'container',
type: 'line',
},
xAxis: {
title: {
text: 'Year'
}
},
yAxis: {
title: {
text: 'Number'
},
},
series: [{
data: series
}],
});
});
});
Checkout the live demo below:
const data = [{
"Year": 2016,
"Number": 41
}, {
"Year": 2017,
"Number": 512
}, {
"Year": 2018,
"Number": 1895
}, {
"Year": 2019,
"Number": 3132
}];
const series = data.map(record => [record.Year, record.Number])
Highcharts.chart('container', {
chart: {
renderTo: 'container',
type: 'line',
},
xAxis: {
title: {
text: 'Year'
}
},
yAxis: {
title: {
text: 'Number'
},
},
series: [{
data: series
}],
});
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/series-label.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container"></div>

Related

Highcharts Range Selector does not work with multiple series

I have a highchart/highstock where I get my data from a php file. My problem is that If I'm using multiple series the RangeSelector Buttons do not work (In the example the 1h buttno (1 hour) should work. Example: https://jsfiddle.net/mymarcelsql/8xL34qyk/15/
That's my File:
<?php
require("php/00connection.php");
$sql = $conn->query("SELECT read_tickets, write_tickets, epoch_time FROM tickets_available ORDER BY epoch_time;")->fetchAll();
foreach ($sql as $row) {
$read_tickets[] = $row['read_tickets'];
$write_tickets[] = $row['write_tickets'];
}
?>
<script type="text/javascript">
$(document).ready(function() {
var categoriesDate = [ <?php foreach ($sql as $row) { ?>
'<?php $date = $row['epoch_time'] / 1000; echo (date('Y-m-d H:i', $date)) ?>',
<?php } ?>
];
var seriesReadTickets = [ <?php echo join($read_tickets, ',') ?> ];
var seriesWriteTickets = [ <?php echo join($write_tickets, ',') ?> ];
var options ={
chart: {
renderTo: 'tickets',
type: 'line',
zoomType: 'x',
setSize: 400
},
title: {
text: "Memory"
},
xAxis: {
categories: categoriesDate,
title: {
text: "Datetime"
},
type:'datetime',
labels: {
format: '{value:%Y-%m-%d %H:%M}',
}
},
yAxis: {
title: {
text: 'Available Tickets'
}
},
rangeSelector: {
enabled: true,
inputEnabled: false,
buttonPosition: {
align: 'right'
},
labelStyle: {
display: 'none'
},
buttons: [
{
type: 'hour',
count: 1,
text: '1h'
},
{
type: 'day',
count: 1,
text: '1d'
},
{
type: 'month',
count: 1,
text: '1m'
},
{
type: 'month',
count: 6,
text: '6m'
},
{
type: 'year',
count: 1,
text: '1y'
},
{
type: 'all',
text: 'All'
}
]
},
tooltip: {
//crosshairs: true,
shared: true,
valueSuffix: '',
xDateFormat: '%Y-%m-%d %H:%M'
},
series: [{
name: 'Read Tickets',
data: seriesReadTickets
}, {
name: 'Write Tickets',
data: seriesWriteTickets
}]
};
var chart = new Highcharts.Chart(options);
});
</script>
But If I use a single series the buttons are working correctly.
Thanks for your help!
Using xAxis.categories automatically sets a type of the axis to category and the range selector feature works only with the datetime axis type.
You need to convert your data to [x, y] format and use the datetime axis type.
API Reference: https://api.highcharts.com/highcharts/series.line.data

Stacked y-Axis on Highcharts, how to make it one?

I successfully created a charts with two y axis using Highcharts JS Library.
However you can see the y-Axis is stacked (Fahrenheit and temperature), is it possible to merge it to one ?
Here is my code.
<script type="text/javascript">
$(function () {
$('#container').highcharts({
chart: {
type: 'line'
},
time: {
timezone: 'Australia/Brisbane'
},
title: {
text: 'Temperature Graph'
},
xAxis: {
type: 'datetime',
categories: <?php echo json_encode($tgl, JSON_NUMERIC_CHECK); ?>,
title: {
text: 'Dates'
},
},
yAxis: [{
title: {
text: 'temperature'
}
}, {
title: {
text: 'Fahrenheit'
}
}],
series: [{
name: 'Celcius',
data: <?php echo json_encode($suhu, JSON_NUMERIC_CHECK);?>
}, {
name: 'Fahrenheit',
data: <?php echo json_encode($lembap, JSON_NUMERIC_CHECK); ?>,
yAxis: 1
}]
});
});
</script>
You can render this chart with only one yAxis and use the labels.formatter callback to format the displaying labels and show also the Fahrenheit values.
Demo: https://jsfiddle.net/BlackLabel/L8e9g1n3/
labels: {
formatter() {
let fahrenheitValue = 1.8 * this.value + 32;
return this.value + " / " + fahrenheitValue
}
}
API: https://api.highcharts.com/highcharts/yAxis.labels.formatter
If you need you can customize the tooltip in the same way by using the tooltip.formatter.
API: https://api.highcharts.com/highcharts/tooltip.formatter

How do i set the X-Axis as Date Array in highcharts.js simple highcharts.chart plot or .stockChart?

I can succesffuly chart the data in a table on mysql
$sql = "SELECT TradeDate as date, LScore2 as L FROM levermann_kurz WHERE Stock_short='MSFT' ORDER BY TradeDate desc";
$stock2 = mysqli_query($mysqli,$sql);
$stock2 = mysqli_fetch_all($stock2,MYSQLI_ASSOC);
$stock2 = json_encode(array_column($stock2,'L'),JSON_NUMERIC_CHECK);
and the body
<script type="text/javascript">
// load("getdata.php")
var data_stock1 = <?php echo $stock1; ?>;
var data_stock2 = <?php echo $stock2; ?>;
Highcharts.chart('container', {
title: {
text: 'Levermann Scores'
},
subtitle: {
text: 'TradeFlags'
},
// xAxis: {
// categories: dates
// },
yAxis: {
title: {
text: 'Levermann Score'
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
plotOptions: {
series: {
label: {
connectorAllowed: false
},
//pointStart: 0
}
},
series: [{
name: 'AAPL',
data: data_stock1
}, {
name: 'MSFT',
data: data_stock2
// }, {
// name: 'External Data',
// data: [null, null, 7988, 12169, 15112, 22452, 34400, 34227]
}],
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}]
}
});
</script>
</body>
But just can't get it to display the Date array as the x-Axis
It just has values 0,1,2,3,4,... etc.
What am i doing wrong? How do you set the x-axis array in the highchart plot?
I thought you could simply pass through a 2 column array with Dates in the first column and Values in the second column ?
Please help!
I have looked on highcharts documentation but it doesnt seem to explain to me how i should pass the data to the chart container. which format it should be?
CONSOLE LOG:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://code.highcharts.com/modules/series-label.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
</head>
<body>
<div id="container" style="height: 400px; max-width: 800px"></div>
<script type="text/javascript">
// load("getdata.php")
var data_stock1 = [3,2,2,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,2,3,2,3,2,2,1,-1,0,0,0,0,0,1,1,0,0,-1,0,-1,-1,-1,-1,-1,0,0];
var data_stock2 = [2,3,2,2,2,2,2,2,2,2,2,2,2,1,2,2,3,2,3,3,1,2,0,2,2,2,1,2,2,2,2,2,2,1,2,2,1,2,2,2,2,1,1,2];
var data_datearray = ["2018-05-25","2018-06-01","2018-06-08","2018-06-15","2018-06-22","2018-06-27","2018-07-06","2018-07-20","2018-07-27","2018-08-03","2018-08-10","2018-08-17","2018-08-24","2018-08-31","2018-09-07","2018-09-14","2018-09-21","2018-09-28","2018-10-05","2018-10-12","2018-10-19","2018-10-26","2018-11-02","2018-11-09","2018-11-16","2018-11-23","2018-11-30","2018-12-07","2018-12-14","2018-12-21","2018-12-28","2019-01-04","2019-01-11","2019-01-18","2019-01-25","2019-02-01","2019-02-08","2019-02-15","2019-02-22","2019-03-01","2019-03-08","2019-03-15","2019-03-22","2019-03-29"];
//var seriesOptions = [], seriesCounter = 0, names = ['MSFT', 'AAPL', 'GOOG'];
/**
* Create the chart when all data is loaded
* #returns {undefined}
*/
//function createChart() {
Highcharts.stockChart('container', {
///
title: {
text: 'Levermann Scores'
},
xAxis: {
type: 'datetime',
categories: data_datearray
},
series: [{
name: 'AAPL',
data: data_stock1
}, {
name: 'MSFT',
data: data_stock2
}]
////
// responsive: {
// rules: [{
// condition: {
// maxWidth: 500
// },
// chartOptions: {
// legend: {
// layout: 'horizontal',
// align: 'center',
// verticalAlign: 'bottom'
// }
// }
// }]
// }
});
// end of container }];
//}
console.log(data_stock1)
</script>
</body>
i can get the date into this format with two columns but it wont work in the chart
var data_dual = [{"date":"2018-05-25","L":"3"},{"date":"2018-06-01","L":"2"},{"date":"2018-06-08","L":"2"},{"date":"2018-06-15","L":"3"},{"date":"2018-06-22","L":"3"},{"date":"2018-06-27","L":"3"},{"date":"2018-07-06","L":"3"},{"date":"2018-07-20","L":"3"},{"date":"2018-07-27","L":"3"},{"date":"2018-08-03","L":"3"},{"date":"2018-08-10","L":"3"},{"date":"2018-08-17","L":"3"},{"date":"2018-08-24","L":"3"},{"date":"2018-08-31","L":"3"},{"date":"2018-09-07","L":"3"},{"date":"2018-09-14","L":"2"},{"date":"2018-09-21","L":"3"},{"date":"2018-09-28","L":"3"},{"date":"2018-10-05","L":"2"},{"date":"2018-10-12","L":"3"},{"date":"2018-10-19","L":"2"},{"date":"2018-10-26","L":"3"},{"date":"2018-11-02","L":"2"},{"date":"2018-11-09","L":"2"},{"date":"2018-11-16","L":"1"},{"date":"2018-11-23","L":"-1"},{"date":"2018-11-30","L":"0"},{"date":"2018-12-07","L":"0"},{"date":"2018-12-14","L":"0"},{"date":"2018-12-21","L":"0"},{"date":"2018-12-28","L":"0"},{"date":"2019-01-04","L":"1"},{"date":"2019-01-11","L":"1"},{"date":"2019-01-18","L":"0"},{"date":"2019-01-25","L":"0"},{"date":"2019-02-01","L":"-1"},{"date":"2019-02-08","L":"0"},{"date":"2019-02-15","L":"-1"},{"date":"2019-02-22","L":"-1"},{"date":"2019-03-01","L":"-1"},{"date":"2019-03-08","L":"-1"},{"date":"2019-03-15","L":"-1"},{"date":"2019-03-22","L":"0"},{"date":"2019-03-29","L":"0"}];
or using UNIX_TIMESTAMP i converted the date format into timestamps:
var data_dual = [{"date":"1527206400","L":"3"},{"date":"1527811200","L":"2"},{"date":"1528416000","L":"2"},{"date":"1529020800","L":"3"},{"date":"1529625600","L":"3"},{"date":"1530057600","L":"3"},{"date":"1530835200","L":"3"},{"date":"1532044800","L":"3"},{"date":"1532649600","L":"3"},{"date":"1533254400","L":"3"},{"date":"1533859200","L":"3"},{"date":"1534464000","L":"3"},{"date":"1535068800","L":"3"},{"date":"1535673600","L":"3"},{"date":"1536278400","L":"3"},{"date":"1536883200","L":"2"},{"date":"1537488000","L":"3"},{"date":"1538092800","L":"3"},{"date":"1538697600","L":"2"},{"date":"1539302400","L":"3"},{"date":"1539907200","L":"2"},{"date":"1540512000","L":"3"},{"date":"1541116800","L":"2"},{"date":"1541721600","L":"2"},{"date":"1542326400","L":"1"},{"date":"1542931200","L":"-1"},{"date":"1543536000","L":"0"},{"date":"1544140800","L":"0"},{"date":"1544745600","L":"0"},{"date":"1545350400","L":"0"},{"date":"1545955200","L":"0"},{"date":"1546560000","L":"1"},{"date":"1547164800","L":"1"},{"date":"1547769600","L":"0"},{"date":"1548374400","L":"0"},{"date":"1548979200","L":"-1"},{"date":"1549584000","L":"0"},{"date":"1550188800","L":"-1"},{"date":"1550793600","L":"-1"},{"date":"1551398400","L":"-1"},{"date":"1552003200","L":"-1"},{"date":"1552608000","L":"-1"},{"date":"1553212800","L":"0"},{"date":"1553817600","L":"0"}];
but using this array data_dual in the series will just render a chart with blank.
You need to use a datetime axis and provide dates as timestamps or as a Date objects, in the first elemets of the data array:
Highcharts.chart('container', {
xAxis: {
type: 'datetime'
},
series: [{
data: [
[1262304000000, 29.9],
[1267401600000, 71.5],
[1270080000000, 106.4]
]
}]
});
Or as an object:
series: [{
data: [{
x: 1262304000000,
y: 29.9
},
{
x: 1267401600000,
y: 71.5
},
{
x: 1270080000000,
y: 106.4
}
]
}]
Live demo: http://jsfiddle.net/BlackLabel/7tov823n/
API Reference: https://api.highcharts.com/highcharts/series.column.data

Javascript variable with Comma separated values not working in HighChart

I have been using highchart for graphical display of my records. HighChart works fine with my php variable with comma separated values in it. However, I couldn't get this done using javascript variable with comma separated values. Please help me with this. Your help is much appreciated. Thanks. My codes are shown below.
Javascript
<script type="text/javascript">
var res = [];
var data_graph = [];
function show_graphics(){
$.post("<?php echo base_url(); ?>main_controller/show_monthly_analytics_ajax", '', function(data){
if( data.notify == "Success" ){
Object.keys(data.upload_data).forEach(function(key) {
res.push(data.upload_data[key]);
});
data_graph = res.join(",");
console.log(data_graph );
} else{
console.log(data.notify);
}
},'json');
$('#container').highcharts({
chart: {
type: 'column',
margin: 75,
options3d: {
enabled: true,
alpha: 10,
beta: 25,
depth: 70
}
},
title: {
text: '3D chart with null values'
},
subtitle: {
text: 'Notice the difference between a 0 value and a null point'
},
plotOptions: {
column: {
depth: 25
}
},
xAxis: {
categories: Highcharts.getOptions().lang.shortMonths
},
yAxis: {
title: {
text: null
}
},
series: [{
name: 'Sales',
data: [data_graph]
}]
});
}
</script>
When I look at the console, the values being showed of the variable array data_graph seems right but the chart never showed a graph. What is the problem with this?
Modification
<script type="text/javascript">
var res = [];
function show_graphics(){
$.post("<?php echo base_url(); ?>main_controller/show_monthly_analytics_ajax", '', function(data){
if( data.notify == "Success" ){
Object.keys(data.upload_data).forEach(function(key) {
res.push(data.upload_data[key]);
});
//aa = res.join(",");
console.log(res);
} else{
console.log(data.notify);
}
},'json');
$('#container').highcharts({
chart: {
type: 'column',
margin: 75,
options3d: {
enabled: true,
alpha: 10,
beta: 25,
depth: 70
}
},
title: {
text: '3D chart with null values'
},
subtitle: {
text: 'Notice the difference between a 0 value and a null point'
},
plotOptions: {
column: {
depth: 25
}
},
xAxis: {
categories: Highcharts.getOptions().lang.shortMonths
},
yAxis: {
title: {
text: null
}
},
series: [{
name: 'Sales',
data: [res]
}]
});
}
</script>
Response
The data part/section for series property should be an array of numbers.
According to your explanation, your implementation is as if you would have the following:
series: [{
name: 'Sales',
data: ['1, 2, 1, 0'] // this is an array with one string element, which is wrong
}]
But, it should be:
series: [{
name: 'Sales',
data: [1, 2, 1, 0]
}]
See JSfiddle demo here
EDIT
Besides the change that I suggested above, consider that the $.post call is an async execution. Then, you should only draw the chart when data is 'ready' by moving $('#container').highcharts(...) block inside the success callback as follows:
if( data.notify == "Success" ){
Object.keys(data.upload_data).forEach(function(key) {
res.push(data.upload_data[key]);
});
$('#container').highcharts({
...
...
series: [{
name: 'Sales',
data: res
}]
});
} else {
console.log(data.notify);
}

Add tag "series:" into Highcharts, from the response server JSON

I try to create a chart with Highcharts, but I can not fill the field "series" with the response returned from the server with PHP. The answer is in JSON format. The chart is not rendered, it goes white background. I pass the code and line of highchart JSON returned by the server. Thank you very much in advance. I am newbie, please have mercy.
I paste her the 2 codes:
SERVER SIDE PHP:
$arr = array();
while ($row_RecordsetTabla = mysql_fetch_assoc($RecordsetTabla))
{
$fecha = $row_RecordsetTabla['fecha'];
$hora = $row_RecordsetTabla['hora'];
$estado = $row_RecordsetTabla['estado'];
$arregloFecha = date_format(new DateTime($fecha),"Y,m,d");
$arregloHora = date_format(new DateTime($hora),"H,i");
$arr[] = array("Date.UTC(".$arregloFecha.",".$arregloHora.")", $estado);
}
$arr2[] = array('data' => $arr);
echo json_encode($arr2);
RESPONSE SERVER JSON:
[{"data":[["Date.UTC(2014,03,27,12,00)","2"],["Date.UTC(2014,04,01,19,10)","1"], ["Date.UTC(2014,04,01,15,44)","1"]]}]
CLIENT SIDE JAVASCRIPT HIGHCHARTS CODE:
$.get("mostrarStatsDispositivo.php", {idDispositivo:"2", numeroDispositivo:"hola"}, function(data){
chart = new Highcharts.Chart({
chart: {`enter code here`
renderTo: 'divStatsDispositivo',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Gráfica de actividad'
},
tooltip: {
enabled: false,
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats : {
hour: '%H',
}
},
yAxis: {
categories: [ 'APAGADO', 'ACTIVO', 'ALARMA'],
title: {
text: 'ESTADO'
},
min: 0
},
series : [{
name : 'grafica',
type : 'line',
data : data, //<--------- NOT WORKING?¿
}]
});
},"json");
....thanks!
You've got a couple of problems going on:
The data you want is actually data[0].data
Your data is not string data but is wrapped in quotes.
Highcharts expects datetime data to be ordered (yours is not).
When I change those things, it works:
$(function () {
var data = [{"data":[[Date.UTC(2014,03,27,12,00),2],[Date.UTC(2014,04,01,15,44),1], [Date.UTC(2014,04,01,19,10),1]]}],
chart = new Highcharts.Chart({
chart: {
renderTo: 'divStatsDispositivo',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Gráfica de actividad'
},
tooltip: {
enabled: false,
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats : {
hour: '%H',
}
},
yAxis: {
categories: [ 'APAGADO', 'ACTIVO', 'ALARMA'],
title: {
text: 'ESTADO'
},
min: 0
},
series : [{
name : 'grafica',
type : 'line',
data : data[0].data,
}]
});
});
http://jsfiddle.net/fUhEj/1/

Categories