Access and chart through perl arrays - javascript

I am trying to write code this way in perl.
\$('#AmpCovPlot').highcharts({
var amp_name = new Array[$amp];
var amp_cov = new Array[$cov]
chart: {
type: 'line'
},
title: {
text: 'Average cov'
},
xAxis: {
categories: [amp_name]
},
yAxis: {
title: {
text: 'Amp name'
}
},
series: [{
name: [amp_name]
data: [amp_cov]
}]
});
so $amp and $cov are perl variables containing array elements, generated by statement :
my $Cov=join(",",#cov);
And I am getting "Uncaught SyntaxError: Unexpected Identifier". I know I am doing a blunder, and I am new to javascript.
Can somebody let me know how to fix this?
Thanks!!!

"Unexpected Identifier" is a hint for invalid Javascript. In your case, i think you print the Javascript Code without double quotes qq{}, to be more precise: You print a $ where no $ is allowed or you dont print a $ where a $ is expected.
When you just Copy + Pasted your Javascript code, you have a syntax Error as well:
var amp_cov = new Array[$cov] // no semicolon ;
// what is the following part for? you dont really assign that stuff to
// something .... seems wrong
chart: {
type: 'line'
},
title: {
text: 'Average cov'
},
xAxis: {
categories: [amp_name]
},
yAxis: {
title: {
text: 'Amp name'
}
},
series: [{
name: [amp_name]
data: [amp_cov]
}]
The next part is the join of the Perl Array. You need to quote the Variables inside the Javascript as well:
var array = ['a','b','c'];
So your join need to be something like:
my $cov = join q{,}, map {qq{'$_'}} #cov;
Which just mean, that you first add single quotes to each element in #cov and then join all with ,

You are defining variables inside object, which is not proper for JS:
$('#AmpCovPlot').highcharts({
var amp_name = new Array[$amp]; // not here!
var amp_cov = new Array[$cov] // not here!
chart: {
type: 'line'
},
title: {
text: 'Average cov'
},
xAxis: {
categories: [amp_name]
},
yAxis: {
title: {
text: 'Amp name'
}
},
series: [{
name: [amp_name]
data: [amp_cov]
}]
});
This should be done this way:
var amp_name = new Array[$amp]; // here define variables
var amp_cov = new Array[$cov]; // here define variables
$('#AmpCovPlot').highcharts({ ... }); // and create chart

Related

Adding items in the nested array of React state

I'm trying to add new items to an array of an object that resides in another object of a state. Pretty nested.
So I tried the following way...
// The initial data
[options, setOptions] = useState({
name: 'Name goes here'
type: 'type goes here'
series : [{
type: 'series type',
label: 'series label'
})
Now I want to add another object inside the object of series array with useEffect(). And I tried:
useEffect(() => {
// other functionalities goes here
setOptions({
...options, // for copying previous data outside of series
series: [{
...options.series, //this is for copying previous data of series
tooltip: {
enable: true,
}]
})
}, [refreshData])
The way I'm copying ...options works absolutely fine, But when I try to copy ...options.series it adds a new copied object inside the object of series array like the following:
{
name: 'Name goes here' //fine
type: 'type goes here' //fine
series: [{
{type: 'series type', label: 'series label'}, //not fine
tooltip: {enable: true} //not fine
//what I want is: to have previous object data and tooltip appended as another item
}]
}
The way I want the object to be is:
{
name: 'Name goes here' //fine
type: 'type goes here' //fine
series: [{
type: 'series type',
label: 'series label'
tooltip: {enable: true}
}]
}
Can Anybody help me regarding this. I would appreciate any help..
Thanks
here is sample of what you are trying to achieve .
const d = {
name: 'Name goes here',
type: 'type goes here',
series : [{
type: 'series type',
label: 'series label'
}]
}
const newD = {
...d,
series: [
{
...d.series[0], // problem is here
tooltip: {
enable: true,
}
}
]
}
console.log (newD)

I cant save my highchart chart data in localStorage

I cant save data in localstorage, I get the result [object Object],[object Object],[object Object]
Here is the code
var usersonline = null;
var maxonline = 50;
Highcharts.stockChart('container', {
chart: {
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.round(usersonline);
series.addPoint([x, y], true, false);
}, 1000);
}
}
},
time: {
useUTC: false
},
rangeSelector: {
buttons: [{
count: 1,
type: 'hour',
text: '1H'
}, {
count: 3,
type: 'hour',
text: '3H'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: false,
selected: 2
},
title: {
text: 'Live Chart of Players Online'
},
exporting: {
enabled: false
},
yAxis: {
title: 'Players Online',
min: 0,
plotLines: [{
color: 'red', // Color value
label: {
text: "Max Player Line"
},
value: maxonline, // Value of where the line will appear
width: 2 // Width of the line
}]
},
series: [{
name: 'Players Online',
connectNulls: false,
data: (function () {
var data = [],
time = (new Date()).getTime(),
i;
if (typeof(Storage) !== "undefined") {
if (localStorage.getItem("chartdata") === null) {
localStorage.setItem('chartdata',[])
data = []
console.log("No Data Found, Creating Some!")
} else {
data = JSON.parse(localStorage.getItem('chartdata'))
console.log("Chart Data Loaded.")
}
} else {
console.log("localStorage is not Supported. Saving Chart Data will not work.")
}
// generate an array of random data
window.onbeforeunload = function(){
console.log("Chart data Saved")
localStorage.chartdata = JSON.stringify(data)
}
return data;
}())
}],
lang: {
noData: "No Data."
},
noData: {
style: {
fontWeight: 'bold',
fontSize: '40px',
color: '#303030'
}
}
});
If I refresh the page it shows the chart as blank and It doesnt display "No Data" so there is data there but it is broken. What I want to happen is When I refresh the page it will keep the data, even when the browser or computer gets restarted.
Is there any solution to this problem, I tried multiple ways but none of them work.
This is a live data chart that I need to save data so The Chart doesnt go blank if you accidently refresh the page.
So the reason why when you get the item it says [Object object] is because localStorage.setItem accepts a DOMString, not an object. setItem will use toString to coerce values into a string, and Object.prototype.toString will always be [object Object].
https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem
You need to use JSON.stringify to convert your array into a valid JSON string in your localStorage.setItem function call and then use JSON.parse to parse that string when you use localStorage.getItem.
const loki = { "type": "dog", "name": "Loki" }
// Sets [object Object] in local storage
localStorage.setItem("lokiKey", loki)
// Sets "{"type":"dog","name":"Loki"}" in local storage
localStorage.setItem("lokiKey", JSON.stringify(loki))
Hope this helps!
Did you try to use myChart.addSeries ? If Series have been changed you should calling method redraw

highcharts doesn't read data, works with fake data

I'm trying to make visualization of the voltage, Array has 1k elements but I'm testing it on first 10 for now, the thing is that It doesn't display anything, what's more interesting when I use fake date which is commented out now, It shows chart properly. I thought that perhaps there is some problem with array so tried to use Array.from but it also brought no effect, here is my code:
.then(function(res) {
var averageVoltage = []
var inputVoltage = []
var date = []
for (var i = 0; i < 10; i++) {
if (res[i].average_volatage !== undefined) {
averageVoltage.push(res[i].average_volatage)
date.push(res[i].timestamp)
}
}
console.log(averageVoltage)
console.log(date)
Highcharts.chart('battery_chart', {
chart: {
type: 'line'
},
title: {
text: id
},
yAxis: {
title: {
text: 'Measurement'
},
},
xAxis: {
categories: date
},
series: [{
name: 'Average Voltage',
data: averageVoltage
// data: [12283, 12283, 12281, 12280, 12282, 12283, 12281, 12282, 12281, 12280]
},
]
});
and that's how array is shown in console.log:
Your array should show up as [12283, 12281, 12280, etc.] in console as well, instead it shows up as [Number, Number, ...]. Try changing this line:
averageVoltage.push(res[i].average_volatage)
to:
averageVoltage.push(parseInt(res[i].average_volatage))
Additionally, instead of using dates as categories, it could be easier to use the highchart datetime axis. This would let you manipulate how you want the date displayed, have several series with different timestamps in one graph, and many other things. To get this to work, you could do this:
.then(function(res) {
var averageVoltage = []
var inputVoltage = []
for (var i = 0; i < 10; i++) {
if (res[i].average_volatage !== undefined) {
averageVoltage.push({x: new Date(res[i].timestamp).getTime(), y: parseInt(res[i].average_volatage)})
}
}
console.log(averageVoltage)
Highcharts.chart('battery_chart', {
chart: {
type: 'line'
},
title: {
text: id
},
yAxis: {
title: {
text: 'Measurement'
},
},
xAxis: {
type: 'datetime'
},
series: [{
name: 'Average Voltage',
data: averageVoltage
},
]
});

how can i handle my json elements

Here is my json file
{
id: '81224112234234222223422229',
type: 'message',
message: 'vacation',
attachments: [
{
type: 'template',
elements: [
{
id: '123123123123123',
title: 'job',
text: 'job',
properties: {
code: 'IO002',
value: 'messenger/IO001,messenger2(IO)/IO002,messenger3(IO)/IO003'
}
},
{
id: '123123123123123',
title: 'Date',
text: 'date',
properties: {
code: '2017-11-09~2017-11-09',
value: '2017-11-09~2017-11-09'
}
},
{
id: '123123123123123',
title: 'Sequence',
text: 'sequence',
properties: {
code: '1',
value: '1process/1,2process/1,3process/1'
}
}
]
}
],
module: 'temp'
}
i am using react.js and i want to extract all properties
result
job code: I0002
job value:messenger/IO001,messenger2(IO)/IO002,messenger3(IO)/IO003
date code:2017-11-09~2017-11-09
date value:2017-11-09~2017-11-09
sequence code:1
sequence value:1process/1,2process/1,3process/1
i tried to execute like this
const job=elements.filter(x=>x.text==='job');
const date=elements.filter(x=>x.text==='date');
const sequence=elements.filter(x=>x.text==='sequence');
is it proper way to use filter or another way to extract data from json file?
i am new to react.js and es6,javascript.so i have no idea to display each property.
how can i solve my problem? pz give me a tip.i want to extract properties
You can use
var yourobject=JSON.parse(jsondata);
const job=yourobject.job;

Failed to load graph (chartjs) from ajax returned JSON

I am using chartjs library for chart generation in html. My HTML, jQuery and PHP are OK, the problem is, when I try to push JSON generated with PHP with ajax call and call the function for graph generation - i have an error (invalid character in JSON). So my code looks like this:
PHP:
$queryPortals = "SELECT description,count(*) AS count FROM portals WHERE ".$portals." AND id<900 GROUP BY description";
$resultPortals = mysqli_query($conn,$queryPortals);
while ($ar = mysqli_fetch_array($resultPortals)) {
$rows[] = "{category: '".$ar['description']."', value: ".$ar['count']."}";
}
echo json_encode($rows,JSON_NUMERIC_CHECK);
This code returns this JSON:
[
"{category: 'Blog', value: 1}",
"{category: 'Portal', value: 1}"
]
My ajax call looks like this:
$.ajax({
type: 'GET',
dataType: 'json',
url: 'class/portalAnalysisGetGraphs.php',
data: 'portals='+portals,
success: function(html){
drawPie(html);
}
});
My drawPie function looks like this:
function drawPie(html)
{
$("#chartContainer").dxPieChart({
dataSource: html,
series: {
argumentField: 'category',
valueField: 'value',
label: {
visible: true,
connector: {
visible: true
}
}
},
tooltip: {
enabled: true,
percentPrecision: 2,
customizeText: function (value) {
return value.percentText;
}
},
title: {
text: 'Portal types'
},
legend: {
horizontalAlignment: 'center',
verticalAlignment: 'bottom'
}
});
};
There is an error in parsing JSON. I've tried to build JSON in PHP withous double quotes, I tried javascript functzion JSON_parse(html) - no luck.
When I put data directly to drawPie function, then it's ok. Direct data input example:
var html= [
{category: 'Blog', value: 1},
{category: 'Portals', value: 1}
];
Please help...

Categories