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 ?>',
Related
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.
i have this code for bar chart but i want to load the data for mysql database
/*
* BAR CHART
* ---------
*/
var bar_data = {
data: [["20-30", 10], ["31-40", 8], ["41-50", 4], ["51-60", 13]],
color: "#3c8dbc"
};
$.plot("#bar-chart", [bar_data], {
grid: {
borderWidth: 1,
borderColor: "#f3f3f3",
tickColor: "#f3f3f3"
},
series: {
bars: {
show: true,
barWidth: 0.5,
align: "center"
}
},
xaxis: {
mode: "categories",
tickLength: 0
}
});
/* END BAR CHART */
There are some hacky ways of using json_encode to output a PHP array in between some <script> tags as one solution.
The better solution though is often to use AJAX to request the data back as JSON and initialize your graph from that. In this way, you are not creating global javascript data variables outside of your javascript.
I'm trying to get my xAxis in Highcharts to use the 'datetime' format instead of regular categories, but I'm not sure on how to do this. Please check the following picture to see what I mean:
http://i.stack.imgur.com/qCOb4.png
Output from data.php:
[
{"name":"datetime","data":[1439929080000,1439929140000,1439929200000, ...
{"name":"krypTemp","data":[17,17.3,17.2,17.3,17.2,17.2,17.2,17.2,17.2, ...
{"name":"vindTemp","data":[19,18.9,18.9,18.8,18.8,18.7,18.7,18.7,18.7, ...
{"name":"uteTemp","data":[15,15.5,15.5,15.4,15.4,15.4,15.3,15.4,15.3, ...
{"name":"krypFukt","data":[59,59,59,59,59,59,59,59,59,59,59,59,59,59, ...
{"name":"vindFukt","data":[49,49,50,50,50,50,50,50,50,50,50,50,50,50, ...
]
And current configuration for my html page:
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'spline'
},
xAxis: {
type: 'datetime'
},
series: []
}
$.getJSON("data.php", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
options.series[1] = json[2];
options.series[2] = json[3];
options.series[3] = json[4];
options.series[4] = json[5];
chart = new Highcharts.Chart(options);
});
});
I know that datetime and categories conflict with eachother but not how I am supposed to rewrite this "options.xAxis.categories = json[0]['data'];" to fit/be displayed as 'datetime'.
Any help on this would be much appreciated as it is the last step towards my goal :).
In case when you have a datetime type of axis, you cannot use categories, because this is different type.
Replace this line:
options.xAxis.categories = json[0]['data'];
with
options.xAxis.tickPositions = json[0]['data'];
In case when labels are printed as numbers, you can use a labels formatter and use Highcharts.datetime inside.
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; ?>);