Related
I am working on Highcharts using PHP/MYSQL. Data is showing properly in each chart but I tried to change one chart to ajax call in order to reduce page load.
I am generating multiple series data from PHP and displaying them back in the required format but data is not showing(I alerted the data it's coming).
Below is the code of ajax call:
function project_wise_lab(from_date, to_date) {
$.ajax({
type: "POST",
url: 'dashboard/project_wise_labtest',
data: {
from_dte: from_date,
to_dte: to_date
},
success: function(response) {
Highcharts.chart('subcontainer7', {
chart: {
type: 'line',
height: 230,
},
credits: {
enabled: false
},
title: {
text: null
},
xAxis: {
categories: ['Oct 2020', 'Nov 2020', 'Dec 2020', 'Jan 2021', 'Feb 2021', 'Mar 2021', 'Apr 2021', 'May 2021']
},
yAxis: {
min: 0,
title: {
// text: 'Total fruit consumption'
},
stackLabels: {
enabled: false,
style: {
fontWeight: 'bold',
color: ( // theme
Highcharts.defaultOptions.title.style &&
Highcharts.defaultOptions.title.style.color
) || 'gray'
}
}
},
legend: {
align: 'center',
verticalAlign: 'bottom',
backgroundColor: Highcharts.defaultOptions.legend.backgroundColor || 'white',
borderColor: '#CCC',
// borderWidth: 1,
shadow: false
},
tooltip: {
/* headerFormat: '<b>{point.x}</b><br/>',
pointFormat: '{series.name}: {point.y}<br/>Total: {point.stackTotal}'
*/
},
plotOptions: {
column: {
stacking: 'normal',
dataLabels: {
// enabled: true
}
}
},
colors: [
'#4a7fbb',
'#be4c48',
'#97b954',
'#7d6096'
],
series: response
});
console.log(response);
},
error: function(xhr, status, error) {
console.error(xhr);
}
});
}
I have alerted the response and the data is showing in the below format:
{ name : 'FKI',data : [10591,10576,9309,8422,9586,11171,9327,9384] },{ name : 'FKR',data : [4740,3105,2690,3598,3686,4930,3711,3859] },{ name : 'FHR',data : [17190,12757,10837,11944,14083,15748,12544,12494] },{ name : 'FUL',data : [1308,937,1002,1086,1452,1419,1248,1362] },{ name : 'FSW',data : [9535,9102,8689,8420,9941,10915,7273,6930] },{ name : 'FWP',data : [47437,42198,43012,44979,47377,55400,46520,41682] },{ name : 'FGR',data : [2112,1366,1619,1664,2387,2355,1633,1215] }
New Response after update:
[{"name":"FKI","data":{"01-OCT-20":"10591","01-NOV-20":"10576","01-DEC-20":"9309","01-JAN-21":"8422","01-FEB-21":"9586","01-MAR-21":"11171","01-APR-21":"9332","01-MAY-21":"9384"}},{"name":"FKR","data":{"01-OCT-20":"4740","01-NOV-20":"3105","01-DEC-20":"2690","01-JAN-21":"3598","01-FEB-21":"3686","01-MAR-21":"4930","01-APR-21":"3711","01-MAY-21":"3859"}},{"name":"FHR","data":{"01-OCT-20":"17190","01-NOV-20":"12757","01-DEC-20":"10837","01-JAN-21":"11944","01-FEB-21":"14083","01-MAR-21":"15748","01-APR-21":"12544","01-MAY-21":"12494"}},{"name":"FUL","data":{"01-OCT-20":"1308","01-NOV-20":"937","01-DEC-20":"1002","01-JAN-21":"1086","01-FEB-21":"1452","01-MAR-21":"1419","01-APR-21":"1248","01-MAY-21":"1362"}},{"name":"FSW","data":{"01-OCT-20":"9535","01-NOV-20":"9102","01-DEC-20":"8689","01-JAN-21":"8420","01-FEB-21":"9941","01-MAR-21":"10915","01-APR-21":"7273","01-MAY-21":"6930"}},{"name":"FHP","data":{"01-OCT-20":"47437","01-NOV-20":"42198","01-DEC-20":"43012","01-JAN-21":"44979","01-FEB-21":"47377","01-MAR-21":"55400","01-APR-21":"46520","01-MAY-21":"41682"}},{"name":"FGR","data":{"01-OCT-20":"2112","01-NOV-20":"1366","01-DEC-20":"1619","01-JAN-21":"1664","01-FEB-21":"2387","01-MAR-21":"2355","01-APR-21":"1633","01-MAY-21":"1215"}}]
The chart is showing empty, kindly help and let me know to get the issue resolve?
Thanks
You appear to have two problems...
jQuery is interpreting your response as plain text (a string) where Highcharts expects actual JS objects
Your response is not valid JSON so you can't interpret it as such on the client-side. Rule #1 when creating JSON responses is... never roll your own JSON.
I recommend getting PHP to generate valid JSON and respond with the correct Content-type
// Ensure jQuery (or any consumer) knows the response is JSON
header("Content-type: application/json");
// Create a data structure representing the series data
$data = [];
foreach ($project as $key => $value) {
$data[] = [
"name" => $key,
"data" => array_values($value) // you just want the values here, not the keys
];
}
// Respond with JSON
echo json_encode($data);
exit;
Then in your client-side code, you can simply use
series: response
as response will now be a valid JS array
You can also make sure jQuery treats the response as JSON by adding
dataType: "json",
to your $.ajax() options but with the right Content-type response header, jQuery should not need this.
Just an FYI, alert() is terrible for viewing data. The best option would be to use your browser's debugger. The second best option is to use console.log()
I want to get data from an url("http://localhost/icx/test/link.html") contains json data. the data contains is like
[{
"call_time": "0",
"total_inc_traffic": "1363.10",
"total_out_traffic": "88.70"
}, {
..............
.............
}]
the json data "total_inc_traffic" is to be shown in the bar chart y axix
<div id="HT_IGW"></div>
<script src="https://cdn.jsdelivr.net/npm/apexcharts#latest"></script>
<script>
var options = {
chart: {
height: 255,
type: 'bar',
},
plotOptions: {
bar: {
horizontal: false,
columnWidth: '55%',
endingShape: 'rounded'
},
},
dataLabels: {
enabled: false
},
stroke: {
show: true,
width: .5,
colors: ['transparent']
},
series: [{
name: 'Traffic In',
data: [
var ourRequest =new XMLHttpRequest();
ourRequest.open('GET','http://localhost/icx/test/link.html');
ourRequest.onload = function(){
var ourData = JSON.parse(ourRequest.responseText);
let result2 = ourData.map(v => Number(v.total_inc_traffic));
console.log(result2);
};
ourRequest.send();
]
}, {
name: 'Traffic Out',
data: [76, 85, 111, 98, 87, 115, 91, 114, 94,76, 85, 111, 98, 87, 115, 91, 114, 94,76, 85, 111,77, 98, 87]
},
],
xaxis: {
categories: ['1', '', '3', '', '5', '', '7', '', '9','','11', '', '13', '', '15', '', '17', '', '19','','21','','23',''],
},
yaxis: {
},
fill: {
opacity: 1
},
tooltip: {
y: {
formatter: function (val) {
return " " + val + " Calls"
}
}
}
}
var chart = new ApexCharts(
document.querySelector("#HT_IGW"),
options
);
chart.render();
</script>
<script>
var ourRequest =new XMLHttpRequest();
ourRequest.open('GET','http://localhost/icx/test/link.html');
ourRequest.onload = function(){
var ourData = JSON.parse(ourRequest.responseText);
let result = ourData.map(v => Number(v.call_time));
console.log(result);
let result2 = ourData.map(v => Number(v.total_inc_traffic));
console.log(result2);
let result3 = ourData.map(v => Number(v.total_out_traffic));
console.log(result3);
};
ourRequest.send();
</script>
</body>
</html>
I expected the output to be shown in the bar graph data, but it gives error data
My error is this
My expectation is
Can anyone help ??
You have an array initializer in a property definition with statements in it:
series: [{
name: 'Traffic In',
data: [
var ourRequest =new XMLHttpRequest();
ourRequest.open('GET','http://localhost/icx/test/link.html');
ourRequest.onload = function(){
var ourData = JSON.parse(ourRequest.responseText);
let result2 = ourData.map(v => Number(v.total_inc_traffic));
console.log(result2);
};
ourRequest.send();
]
You can't do that. With an array initializer ([...]) you can only have expressions in it separated with commas. The expressions are evaluated to create the values to put in the array.
It's not clear to me what you're trying to do there, but that code probably belongs after the big object initializer creating the options object.
You cannot put a code block (the part starting with "var ourRequest") inside array initializer.
If you need the data obtained from ajax call to become the options.series.data property, you need to either create the options object after the ajax call is done, or create the options without that property and add to it when the ajax call is finished.
Anyway if the server that provides the json endpoint is the same as the one that is rendering the page, you should be able to render that information there right when the page is rendered, bypassing need to call any additional ajax request.
As long as you dont want to also call it to update the information without re-rendering the entire page.
To sort off cap what I'm doing.. I have a loop that creates a table from information pulled from my database. I've setup a superglobal variable inside the loop that assigns one of my table field values to the variable; that part works no problem.
The problem is when I try to call that variable inside the highcharts function, it just doesn't work. The charts don't show up.
$(document).ready(function() {
var $container = $('$global_var');
Highcharts.setOptions({
chart: {
backgroundColor: {
linearGradient: [0, 0, 500, 500],
stops: [
[0, 'rgb(255, 255, 255)'],
[1, 'rgb(240, 240, 255)']
]
},
borderWidth: 2,
plotBackgroundColor: 'rgba(255, 255, 255, .9)',
plotShadow: true,
plotBorderWidth: 1
}
});
var chart1 = new Highcharts.Chart({
chart: {
renderTo: $container,
},
xAxis: {
type: 'datetime'
},
series: [{
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],
pointStart: Date.UTC(2010, 0, 1),
pointInterval: 3600 * 1000 // one hour
}]
});
});
</script>
In the table that's created, I have a <div> inserted with a dynamic ID (same values as the array I'm attempting to use with the highcharts function), which also works. The only issue is that I can't seem to pass the variable to the renderTo part of the highcharts function.
Here's how I'm declaring my superglobal variable inside my table loop (again, works fine):
$GLOBALS['a'] = $row['Name'] . $temp_array;
TL;DR.. If anyone knows how to pass a variable to renderTo in the Highcharts function I'd really love to know how you do it. Hopefully this is enough info, but if not I'll gladly provide what is requested. Thanks!
In renderTo you need to add string not object as you return.
So it should be
var $container = 'global_var', //id of container, string
and in the chart
chart: {
renderTo: $container,
},
If you would like to combine js variable with string from php variable it should be something like:
var $container = '<?php echo $variable ?>',
I want to retrieve values dynamically from the database and plot using Highcharts spline graph. The problem is I cant figure out a way to pass the values to Javascript function without refreshing the whole function, this will plot the whole graph from the scratch. The current code contains an array where it just plots using an array and a random function to generate new values. I want to find a way to insert new values on to that array from the database using PHP. Problem is I don't know how to keep on calling the database query without affecting the graph. Some help on plotting the graph dynamically using the dynamic values from the database would be helpful.
$(function () {
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart;
chart = new Highcharts.Chart({
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);
}
}
},
title: {
text: 'Trend analysis'
},
xAxis: {
labels: {
rotation: 320
},
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
credits:{
enabled:false
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) +'<br/>'+
Highcharts.numberFormat(this.y, 2);
}
},
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++) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
})()
}]
});
});
});
The technique you are looking for is called ajax. This is where the javascript requests more data from the server without the whole page loading. The basic approach is:
The page is loaded and renders the initial chart.
The page then requests additional data fromthe user. In jquery, this is done using a call to$.ajax
The server responds with some more data.
The javascript loads this data into the chart using chart.series.addpoint or chart.series.setData.
Steps 2 to 5 are then repeated at regular intervals.
Highcharts has good article on this here: http://docs.highcharts.com/#preprocessing-live-data with some example code. You will need to amend the php to read the data from your database, and you may want to change the shift logic in the javascript depending on whether you want old points to drop off, or stay on the chart.
If you series isn't too big, it's not unreasonable to return the whole data set each time and use chart.series.setData to replace the entire series, instead of doing it point by point. The API calls you need are documented here: http://api.highcharts.com/highcharts#Series
I had a highcharts temperature gauge working when I put the javascript inline in my php file. However, I wanted to put the highcharts code in an "included" js file. Before, when I coded the javascript inline with the php file, it looked something like this:
// html and php above
// this inline code below works
<script>
$(document).ready(function(){
// here i simply accessed a php variable from
var $temperature_F = <?php echo round((($temp["Temperature"] * 9) / 5) + 32, 1); ?>;
var chart1 = new Highcharts.Chart({
// code initializing everything else in the highchart
series: [{
data: [{
id: 'temperature',
y: $temperature_F, // value taken from php variable
tooltip: {
valueSuffix: ' \xB0F'
}
}]
}]
});
})
</script>
// html and php below
Now, all I did was take this chunk of code, put it in a .js file and "include" it. I now just call a Print function from the php file, defined in my .js file, passing it the php variables I need. Like this:
<script type="text/javascript">
PrintTemperatureChart(1, '<?php echo $temperatureToDisplay; ?>', '<?php echo $dewPointToDisplay; ?>', '<?php echo $relativeHumidityToDisplay; ?>');
</script>
From within this function, I am able to "alert" out the expected php variables that I passed in, however, when I attempt to set "data:" to one of these variables, it breaks the chart. When I replace the variable with a dummy hard-coded value, it works. So I know just about everything else is set up correctly. Here's the function in the .js file:
function PrintTemperatureChart(unitsMode, temperature, dewPoint, relativeHumidity){
alert(unitsMode + ", " + temperature + ", " + dewPoint + ", " + relativeHumidity);
$(function () {
alert("The passed temperature = " + temperature);
var $theTemp = temperature;
var chart1 = new Highcharts.Chart({
chart: {
renderTo: 'Temperature_Chart',
type: 'gauge',
margin: 0
},
title: {
text: 'Temperature'
},
pane: {
startAngle: -150,
endAngle: 150,
background: [{
backgroundColor: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
stops: [
[0, '#FFF'],
[1, '#333']
]
},
borderWidth: 0,
outerRadius: '109%'
}, {
backgroundColor: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
stops: [
[0, '#333'],
[1, '#FFF']
]
},
borderWidth: 1,
outerRadius: '107%'
}, {
// default background
}, {
backgroundColor: '#DDD',
borderWidth: 0,
outerRadius: '105%',
innerRadius: '103%'
}]
},
yAxis: {
title: {
text: '\xB0F'
},
min: 0,
max: 120,
minorTickInterval: 1,
minorTickWidth: 1,
minorTickLength: 5,
minorTickPosition: 'inside',
minorGridLineWidth: 0,
minorTickColor: 'black',
tickInterval: 10,
tickWidth: 2,
tickPosition: 'inside',
tickLength: 10,
tickColor: 'black',
},
series: [{
name: 'Temperature',
data: [$theTemp], // this doesn't work
// this is the js var set to the passed in temperature
// I've also just tried using the param directly
// only a hard coded value will work
// i.e. data: [56],
tooltip: {
valueSuffix: ' \xB0F'
}
}]
});
});
}
I just need to use these variables passed in as data in my chart. Thanks in advance!
By placing single quotes around the PHP code like this:
PrintTemperatureChart(1, '<?php echo $temperatureToDisplay; ?>');
these variables were being passed as strings, which is incompatible with the integer type the "data" field expects in HighCharts. Solution:
PrintTemperatureChart(1, <?php echo $temperatureToDisplay; ?>);