HighCharts: local variable not working in "data:" - php

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; ?>);

Related

ChartJS memory usage

So I've experienced some problems with one of my PHP pages using ChartJS, when I load my charts (Pie/Bar), with a good amount of data, then the google tab on revisit can not respond / say out of memory or something like that. I've read that it should be possible to make ChartJS be garbage-collected by calling .destroy(), but that removes my chart, so I don't know how that should be done?
Is there a proper way to create a chart, and then do some kind of clean-up after, and still show the chart on the webpage?
This is the function for barChart
**function barChart(barChartVal) {
const color = new chartColor();
new Chart(document.getElementById("chart-area-last-5-runs"), {
type: 'bar',
data: {
labels: [barChartVal[5][0], barChartVal[5][1], barChartVal[5][2], barChartVal[5][3], barChartVal[5][4]],
datasets: [{
data: [barChartVal[0][0], barChartVal[0][1], barChartVal[0][2], barChartVal[0][3], barChartVal[0][4]],
label: 'Passed',
backgroundColor: color.green(),
}, {
data: [barChartVal[1][0], barChartVal[1][1], barChartVal[1][2], barChartVal[1][3], barChartVal[1][4]],
label: 'Failed',
backgroundColor: color.red(),
}, {
data: [barChartVal[2][0], barChartVal[2][1], barChartVal[2][2], barChartVal[2][3], barChartVal[2][4]],
label: 'Error',
backgroundColor: color.yellow(),
}, {
data: [barChartVal[3][0], barChartVal[3][1], barChartVal[3][2], barChartVal[3][3], barChartVal[3][4]],
label: 'Not Run',
backgroundColor: color.blue(),
}, {
data: [barChartVal[4][0], barChartVal[4][1], barChartVal[4][2], barChartVal[4][3], barChartVal[4][4]],
label: 'Not Applicable',
backgroundColor: color.black(),
}]
},
options: {
scales: {
xAxes: [{
stacked: true,
ticks: {
display: false //this will remove only the label
}
}],
yAxes: [{ stacked: true }]
},
tooltips: {
/* tooltip text made smaller to longer labels fit */
mode: 'index',
intersect: false,
titleFontSize: 14,
bodyFontSize: 13,
bodySpacing: 0,
titleSpacing: 0,
xPadding: 2,
yPadding: 2,
cornerRadius: 2,
titleMarginBottom: 2
},
hover: {
mode: 'index',
intersect: false
},
animation: false, //No animations
parsing: false,
normalized: true
}
});
}**
Yes you can do something like that, you can transform the chart to an image and display that, then you can delete your chart which will free up the memory. Downside of this will be that its not interactable anymore:
const options = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: 'orange'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
backgroundColor: 'pink'
}
]
},
options: {
animation: false
}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
const chartContainer = document.getElementById('chartJSContainer');
const chartImage = document.getElementById('chartImage');
const chart = new Chart(ctx, options);
const base64Chart = chart.toBase64Image();
// Set image source to chart image
chartImage.src = base64Chart;
// Destroy chart and remove canvas
chart.destroy();
chartContainer.remove();
<body>
<img id="chartImage">
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
</body>

while using json data shows Uncaught SyntaxError: Unexpected token var

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.

Hight Chart Dynamic Json Value is not loading in Series Data Section but Static Value is Loading Finely

Hi I have one issue i was creating one HighChart in this Static values to the series data section is working finely. but The same type value from a dynamic section is not showing.
function getusercategorygraph()
{
$.getJSON('config/alumniusermodes.php',function(data){
//alert(json);
//alert($.parseJSON(data));
//alert(obj);
var finaldata = '[';
var tmp = '';
var chart;
$.each(data, function( index, value ) {
finaldata += '{';
$.each(value, function( index, value ) {
//alert(index);
if(index === 'name')
{
tmp = " " + index + " : '" + value + "', ";
}
else
{
tmp = " " + index + " : " + value + ", ";
}
finaldata += tmp;
//alert("finaldata: " + finaldata);
});
finaldata+='},';
});
finaldata +=']';
//alert(finaldata);
chart = new Highcharts.Chart({
chart: {
/* backgroundColor: {
linearGradient: { x1: 0, y1: 0, x2: 1, y2: 1 },
stops: [
[0, 'rgb(0, 0, 0)'],
[1, 'rgb(0, 0, 0)']
]
},*/
renderTo : 'user-count',
type: 'column',
},
title: {
text: 'Alumni Users By Category Analytics'
},
xAxis: {
color:'#0077CC',
type: 'category'
},
yAxis: {
title: {
text: 'Total Number of Alumni Members'
}
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y} Members'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y} Members</b><br/>'
},
series: [{
name: "Alumni Type",
colorByPoint: true,
//sdata: [{ name : 'Standard', y : 52, },{ name : 'Silver', y : 24, },{ name : 'Gold', y : 20, },{ name : 'Platinum', y : 6, },]
data: [{ name : 'Standard', y : 52, },{ name : 'Silver', y : 24, },{ name : 'Gold', y : 20, },{ name : 'Platinum', y : 6, },]
//data : finaldata,
}],
});
///chart.series[2].data.push(finaldata);
});
}
i am getting final data like this only
[{ name : 'Standard', y : 52, },{ name : 'Silver', y : 24, },{ name : 'Gold', y : 20, },{ name : 'Platinum', y : 6, },]
but i cant load that in this graph but when paste same value in static mode its showing correctly.
now its showinng a blank section only.
I am new to HighCharts Please help. Thanks in advance.
Your code is creating finaldata as a string, when you want to produce an array. You should have better luck with something like this:
// Create a new array
var finaldata = []
var chart;
// Perform your operations
$.each(data, function( index, value ) {
// Create a new hash
var currentItem = {}
// Create the proper values in your hash
$.each(value, function( index, value ) {
currentItem[index] = value;
});
// Push the new hash to the array
finaldata += currentItem;
});
If all of your data is being passed in a way that your old code successfully created the string you shared, then this should build the object for which you are looking.
To test this you may first want to try leaving your code exactly how it is, and parsing the string to JSON:
// Use this instead of 'data : finaldata'
data: JSON.parse( finaldata ),
This will try to turn your string into the objects on which you are trying to operate. That said, it would be in poor form to practice building an array via string manipulation. I would very strongly encourage you to follow the first approach I detailed.
Hi i Found this as For My Query.
var finaldata = [];
$.getJSON('config/alumniusermodes.php',function(data){
// Create a new array
var finaldata = [];
var chart;
var categories = [];
var tools = [];
$.each(data, function( index, value ) {
var currentItem = {}
finaldata.push({
name: value.name,
y: parseFloat(value.y)
});
});
var chart = new Highcharts.Chart({
chart: {
renderTo : 'user-count',
type: 'column',
},
title: {
text: 'Alumni Users By Category Analytics'
},
xAxis: {
color:'#0077CC',
categories: categories
},
yAxis: {
title: {
text: 'Total Number of Alumni Members'
}
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y} Members'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y} Members</b><br/>'
},
series: [{
name: "Alumni Type",
colorByPoint: true,
data : finaldata,
}],
});
});
This is my right coding which solved my issue

Creating dynamic Highcharts based on an array

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 ?>',

Get current date values to own hours

I get values to MySql database everyday at each hour.
I got site with highcharts, but I cant get it to work.
I need to get current day values from MySql organized to own hours.
Here is my Highcharts code:
<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 type="text/javascript">
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'chart',
defaultSeriesType: 'spline'
},
title: {
text: "Today's Values"
},
subtitle: {
text: 'Values by Hour'
},
credits: {
enabled: false
},
xAxis: {
categories: ['12AM', '1AM', '2AM', '3AM', '4AM', '5AM',
'6AM', '7AM', '8AM', '9AM', '10AM', '11AM','12PM', '1PM', '2PM', '3PM', '4PM', '5PM',
'6PM', '7PM', '8PM', '9PM', '10PM', '11PM']
},
yAxis: {
min: 0,
title: {
text: 'Values'
},
labels: {
formatter: function() {
return this.value
}
}
},
tooltip: {
valueDecimals: 2,
crosshairs: true,
shared: true,
formatter: function() {
return '$' + this.y;
}
},
plotOptions: {
spline: {
marker: {
radius: 4,
lineColor: '#666666',
lineWidth: 1
}
}
},
series: [{
name: 'Values',
data: [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
}]
});
});
</script>
Here is pic from MySql database how it looks like
chart
So, I need all values from MySql categorized to own hours at chart.
It should count values + show it at own category, any idea how to do this?
Im stuck with this beacause I dont know how to do this.
I advice to familiar with article about preprocessing data form MySQL http://docs.highcharts.com/#preprocessing-data-from-a-database
You should export your data from php as JSON, then if you would like you use categories for xAxis, you need to parse your JSON and push appropaite data to correct place.Similar with data points in series.

Categories