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>
I have used high chart to present the data. Currently I have one chart that shows montly, yearly, week data and another chart is for 24 hours. What I want is to have a single legend that controls both chart. While googling for solution I found this http://jsfiddle.net/teEQ3/ which seems to be working but as I am naive to javascript I can figure out how to implement this code in my running script.
here is my javascript code for chart1
<script type="text/javascript">
$(document).ready(function() {
var buttons = Highcharts.getOptions().exporting.buttons.contextButton.menuItems;
var options = {
chart: {
renderTo: 'mylineChart',
defaultSeriesType: 'line',
spacingLeft : 60,
zoomType: 'x'
},
title: {
text: 'TPV Line Chart Data',
x: -20 //center
},
rangeSelector:{
enabled:true,
buttons: [{
type: 'month',
count: 1,
text: '1m'
}, {
type: 'month',
count: 6,
text: '6m'
}, {
type: 'year',
count: 1,
text: '1y'
}, {
type: 'all',
count: 1,
text: 'all'
}],
spacingBottom: 40
},
subtitle: {
text: '',
x: -20
},
xAxis: {
gridLineWidth: 0,
type: 'datetime',
dateTimeLabelFormats: {
month: '%b %e, %Y',
year: '%Y'
}
},
credits: {
enabled: false
},
yAxis: [<?php echo join($ylabel, ',') ?>],
tooltip: {
shared: true
},
legend: {
color: 'white',
layout: 'vertical',
align: 'left',
x: -60,
itemHiddenStyle: {
color: "#777"
},
verticalAlign: 'top',
y: 5,
floating: true,
backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'
},
exporting: {
buttons: {
contextButton: {
enabled: false
},
exportButton: {
text: 'Download',
theme: {
fill: '#eee',
stroke: '#fff',
states: {
hover: {
fill: '#fff',
stroke: '#eee'
},
select: {
fill: '#ddd',
stroke: '#0f0'
}
}
},
_titleKey: 'contextButtonTitle',
// Use only the download related menu items from the default context button
menuItems:buttons.slice(2)
},
printButton: {
text: 'Print',
theme: {
fill: '#eee',
stroke: '#fff',
states: {
hover: {
fill: '#fff',
stroke: '#eee'
},
select: {
fill: '#ddd',
stroke: '#0f0'
}
}
},
_titleKey: 'printChart',
onclick: function () {
this.print();
}
}
}
},
series: [<?php echo join($arr, ',') ?>],
}
<?php
$i = 0 ;
$check_temperature = "SELECT * FROM temperature_setting WHERE device_key = '".$session_row['device_key']."'";
$ans = $conn->query($check_temperature);
while($check = $ans->fetch_assoc()){
$check_temp_id = $check['temp_id'];
$check_is_active = $check['is_active'];
for ($j = 1; $j <=15; $j++){
if($check_temp_id == 'temp'.$j.'' && $check_is_active == 1){
?>
myfunction(<?php echo $i++; ?>, 'lineData/tempdata<?php echo $j; ?>.php');
<?php }
}
}
$check_pulse = "SELECT * FROM pulse_setting WHERE device_key = '".$session_row['device_key']."'";
$ans2 = $conn->query($check_pulse);
while($check2 = $ans2->fetch_assoc()){
$check_pulse_id = $check2['pulse_id'];
$check_is_active = $check2['is_active'];
for ($k = 1; $k <=8; $k++){
if($check_pulse_id == 'pulse'.$k.'' && $check_is_active == 1){
?>
myfunction(<?php echo $i++; ?>, 'lineData/pulsedata<?php echo $k; ?>.php');
<?php }
}
}
$check_volt = "SELECT * FROM volt_setting WHERE device_key = '".$session_row['device_key']."'";
$ans3 = $conn->query($check_volt);
while($check3 = $ans3->fetch_assoc()){
$check_volt_id = $check3['volt_id'];
$check_is_active = $check3['is_active'];
for ($v = 1; $v <=4; $v++){
if($check_volt_id == 'volt'.$v.'' && $check_is_active == 1){
?>
myfunction(<?php echo $i++; ?>, 'lineData/voltdata<?php echo $v; ?>.php');
<?php }
}
}
?>
function myfunction(ind, some_file) {
jQuery.get(some_file, null, function(tsv) {
var lines = [];
traffic = [];
try {
// split the data return into lines and parse them
tsv = tsv.split(/\n/g);
jQuery.each(tsv, function(i, line) {
line = line.split(/\t/);
date = Date.parse(line[0] +' UTC');
traffic.push([
date,
parseInt(line[1].replace(',', ''), 10)
]);
});
} catch (e) { }
options.series[ind].data = traffic;
chart = new Highcharts.Chart(options);
});
}
});
</script>
for chart 2
<script type="text/javascript">
var mychart;
$(document).ready(function() {
var buttons = Highcharts.getOptions().exporting.buttons.contextButton.menuItems;
var options = {
chart: {
renderTo: 'box',
defaultSeriesType: 'line',
spacingLeft : 60,
zoomType: 'x'
}, title: {
text: 'TPV Line Chart Data',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
type: 'datetime',
tickInterval: 3600 * 1000, // one hour
tickWidth: 0,
gridLineWidth: 0,
labels: {
align: 'center',
x: -3,
y: 20,
formatter: function() {
return Highcharts.dateFormat('%l%p', this.value);
}
}
},
credits: {
enabled: false
},
yAxis: [<?php echo join($ylabel, ',') ?>],
legend: {
color: 'white',
layout: 'vertical',
align: 'left',
x: -60,
itemHiddenStyle: {
color: "#777"
},
verticalAlign: 'top',
y: 5,
floating: true,
backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'
},/*
plotOptions: {
series: {
events: {
legendItemClick: function (event) {
var XYZ = $('#mylineChart').highcharts(),
series = XYZ.get(this.options.id); //get corresponding series
if (series) {
if (this.visible) {
series.hide();
} else {
series.show();
}
}
}
}
}
},
*/
exporting: {
buttons: {
contextButton: {
enabled: false
},
exportButton: {
text: 'Download',
theme: {
fill: '#eee',
stroke: '#fff',
states: {
hover: {
fill: '#fff',
stroke: '#eee'
},
select: {
fill: '#ddd',
stroke: '#0f0'
}
}
},
_titleKey: 'contextButtonTitle',
// Use only the download related menu items from the default context button
menuItems:buttons.slice(2)
},
printButton: {
text: 'Print',
theme: {
fill: '#eee',
stroke: '#fff',
states: {
hover: {
fill: '#fff',
stroke: '#eee'
},
select: {
fill: '#ddd',
stroke: '#0f0'
}
}
},
_titleKey: 'printChart',
onclick: function () {
this.print();
}
}
}
},
series: [<?php echo join($arr, ',') ?>],
}
<?php
$i = 0 ;
$check_temperature = "SELECT * FROM temperature_setting WHERE device_key = '".$session_row['device_key']."'";
$ans = $conn->query($check_temperature);
while($check = $ans->fetch_assoc()){
$check_temp_id = $check['temp_id'];
$check_is_active = $check['is_active'];
for ($j = 1; $j <=15; $j++){
if($check_temp_id == 'temp'.$j.'' && $check_is_active == 1){
?>
myfunction(<?php echo $i++; ?>, 'lineData/hourly_tempdata<?php echo $j; ?>.php');
<?php }
}
}
$check_pulse = "SELECT * FROM pulse_setting WHERE device_key = '".$session_row['device_key']."'";
$ans2 = $conn->query($check_pulse);
while($check2 = $ans2->fetch_assoc()){
$check_pulse_id = $check2['pulse_id'];
$check_is_active = $check2['is_active'];
for ($k = 1; $k <=8; $k++){
if($check_pulse_id == 'pulse'.$k.'' && $check_is_active == 1){
?>
myfunction(<?php echo $i++; ?>, 'lineData/hourly_pulsedata<?php echo $k; ?>.php');
<?php }
}
}
$check_volt = "SELECT * FROM volt_setting WHERE device_key = '".$session_row['device_key']."'";
$ans3 = $conn->query($check_volt);
while($check3 = $ans3->fetch_assoc()){
$check_volt_id = $check3['volt_id'];
$check_is_active = $check3['is_active'];
for ($v = 1; $v <=4; $v++){
if($check_volt_id == 'volt'.$v.'' && $check_is_active == 1){
?>
myfunction(<?php echo $i++; ?>, 'lineData/hourly_voltdata<?php echo $v; ?>.php');
<?php }
}
}
?>
function myfunction(ind, some_file) {
jQuery.get(some_file, null, function(tsv) {
var lines = [];
traffic = [];
try {
// split the data return into lines and parse them
tsv = tsv.split(/\n/g);
jQuery.each(tsv, function(i, line) {
line = line.split(/\t/);
date = Date.parse(line[0] +' UTC');
traffic.push([
date,
parseInt(line[1].replace(',', ''), 10)
]);
});
} catch (e) { }
options.series[ind].data = traffic;
chart = new Highcharts.Chart(options);
});
}
});
</script>
This is what I am getting currenlty
It's pretty simple if you're reading the API documentation well.
All you have to do is to make the series ID's the same with the other chart and let the second chart legends handle the control. See below:
$(function () {
$('#container1').highcharts({
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
legend: {
enabled: false
},
series: [{
id: 'someId',
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
},{
id: 'someId_',
data: [30.0, 51.5, 206.4, 529.2, 44.0, 76.0, 335.6, 148.5, 216.4, 294.1, 92.6, 60.2]
}]
});
$('#container2').highcharts({
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
plotOptions: {
series: {
events: {
legendItemClick: function (event) {
var XYZ = $('#container1').highcharts(),
series = XYZ.get(this.options.id); //get corresponding series
if (series) {
if (this.visible) {
series.hide();
} else {
series.show();
}
}
}
}
}
},
series: [{
id: 'someId',
name: 'Series 1',
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
},{
id: 'someId_',
name: 'Series 2',
data: [30.0, 51.5, 206.4, 529.2, 44.0, 76.0, 335.6, 148.5, 216.4, 294.1, 92.6, 60.2]
}]
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<div id="container1" style="height: 300px"></div>
<div id="container2" style="height: 300px"></div>
I have a code for a bar chart and it is working well but this code has static values but I want to take the values from a server and every time have a different chart (I mean I dont want to give any values in the code).How can I make that?
This is the code:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.1.0.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; max-width: 800px; height: 400px; margin: 0 auto"></div>
<script>
$(function () {
$('#container').highcharts({
chart: {
type: 'bar'
},
title: {
text: 'Top 10 HashTags'
},
xAxis: {
categories: ['Africa', 'America', 'Asia', 'Europe', 'Oceania'],
title: {
text: null
}
},
yAxis: {
min: 0,
title: {
text: 'Number of repeated hashTags ',
align: 'high'
},
labels: {
overflow: 'justify'
}
},
tooltip: {
valueSuffix: ' millions'
},
plotOptions: {
bar: {
dataLabels: {
enabled: true
}
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -40,
y: 80,
floating: true,
borderWidth: 1,
backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'),
shadow: true
},
credits: {
enabled: false
},
series: [ {
name: 'Year 2012',
data: [1052, 954, 4250, 740, 38]
}]
});
});
</script>
A little example to you. The first column is the xAxis and the others, series. I hope this help you.:
<?php
$sql5 = mysqli_query($bd,'SELECT tx_rend_escolas.ano, tx_rend_escolas.ap_med, tx_rend_escolas.rep_med, tx_rend_escolas.abd_med FROM tx_rend_escolas WHERE tx_rend_escolas.fk_cod_entidade = 21438200 ORDER BY tx_rend_escolas.ano ASC;') or die(mysqli_error());
$linhas5 = mysqli_num_rows($sql5);
$proc4 = array();
$proc5 = array();
$proc6 = array();
$proc7 = array();
while ($docs = mysqli_fetch_assoc($sql5)) {
$proc4[] = "'".$docs['ano']."'";
$proc5[] = $docs['ap_med'];
$proc6[] = $docs['rep_med'];
$proc7[] = $docs['abd_med'];
}
$proc4 = implode(",", $proc4);
$proc5 = implode(",", $proc5);
$proc6 = implode(",", $proc6);
$proc7 = implode(",", $proc7);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<style type="text/css">
${demo.css}
</style>
<script type="text/javascript">
$(function () {
$('#container').highcharts({
chart: {
type: 'area'
},
title: {
text: 'Historic and Estimated Worldwide Population Distribution by Region'
},
subtitle: {
text: 'Source: Wikipedia.org'
},
xAxis: {
categories: [<?php echo $proc4;?>],
tickmarkPlacement: 'on',
title: {
enabled: false
}
},
yAxis: {
title: {
text: 'Percent'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.percentage:.1f}%</b><br/>',
shared: true
},
plotOptions: {
area: {
stacking: 'percent',
lineColor: '#ffffff',
lineWidth: 1,
marker: {
lineWidth: 1,
lineColor: '#ffffff'
}
}
},
series: [{
name: 'Aprovação',
data: [<?php echo $proc5;?>]
}, {
name: 'Reprovação',
data: [<?php echo $proc6;?>]
}, {
name: 'Abandono',
data: [<?php echo $proc7;?>]
}]
});
});
</script>
</head>
<body>
<script src="js/highcharts.js"></script>
<script src="js/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
</body>
</html>
so I have finally came up with the following script that generates a highcharts graph based on data from MySQL.
The actual HTML and Javascript are here:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
function test(year){
$.getJSON("data.php?year="+year, function(json){
options.series[0].data = json['data'];
chart = new Highcharts.Chart(options);
});
}
</script>
<script>
$(function () {
var chart;
$(document).ready(function() {
$.getJSON("data.php?year=2012", function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Revenue vs. Overhead',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
yAxis: {
title: {
text: 'Amount'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
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
},
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>
<button onclick="test('2013')">2013</button>
</body>
</html>
The PHP file then looks like this:
<?php
$con=mysqli_connect("x","x","x","x");
$year = $_GET["year"];
$rows = array();
$rows['name'] = '2012';
$x = mysqli_query($con,"
SELECT Logdatetime, Temp
FROM alldata
WHERE YEAR(Logdatetime)=$year
LIMIT 12"
);
while($r = mysqli_fetch_array($x)){
$rows['data'][] = $r['Temp'];
}
$result = array();
array_push($result,$rows);
print json_encode($result, JSON_NUMERIC_CHECK);
?>
Now the problem is that what happens is that it works and generates the initial graph with a value "2012" as year, but after clicking the button which I wanted to generate 2013, nothing happens.
Any idea where the mistake is? It must be somewhere in the function test(), which I used to trigger the call from the button click, but I have no idea how to fix it.
I am trying to use high chart. I am new to high chart also new to jquery also. I was trying load categories and series into the line chart. This is the code which i am used.
<script type="text/javascript">
$(function () {
function getData(){
alert('fff');
$.ajax({
url:"high_line_data.php",
type:"POST",
success:function(resp){
chart.series[0].setData(resp);
}
});
}
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 25,
events: {
load: getData
}
},
title: {
text: 'Monthly Average Temperature',
x: -20 //center
},
subtitle: {
text: 'Source: WorldClimate.com',
x: -20
},
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
yAxis: {
title: {
text: 'Temperature (°C)'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
valueSuffix: '°C'
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
});
});
</script>
and php script
I am echoing the series result as
name:'Test',
Data : '1,3,4,5'
How can I resolve this. Please help.
parse the output of the php from text to array. highcharts also accepts a direct array of integers as input to plot the data.
hope this will be useful
You should replace your string values with numbers. Obiously you can use JSON format to add points.
Related article about preprocessing data from PHP: http://docs.highcharts.com/#preprocessing