I am using ApexCHartsJS and i want the DATA to show a PHP variable, my PHP variables looks like this '%number%'
i've created variables gra / lis / voc / rea / ave , but the result i get blank chart
<script>
var colors = ['#008FFB', '#00E396', '#FEB019', '#FF4560'];
var gra = ['%AVERAGE_CATEGORY_POINTS_Grammar%'];
var lis = ['%AVERAGE_CATEGORY_POINTS_Listening%'];
var voc = ['%AVERAGE_CATEGORY_POINTS_Vocabulary%'];
var rea = ['%AVERAGE_CATEGORY_POINTS_Reading%'];
var ave = ['%CORRECT_SCORE%'];
var options = {
chart: {
height: 500,
type: 'bar',
events: {
click: function(chart, w, e) {
console.log(chart, w, e )
}
},
},
colors: colors,
plotOptions: {
bar: {
columnWidth: '50%',
distributed: true
}
},
dataLabels: {
enabled: true,
},
series: [{
data: [gra,lis,voc,rea,ave]
}],
xaxis: {
categories: ['Grammar / 15', 'Listening / 15', 'Vocabulary / 15', 'Reading / 15', 'Average %'],
labels: {
style: {
colors: colors,
fontSize: '15px'
}
}
}
}
var chart = new ApexCharts(
document.querySelector("#chart"),
options
);
chart.render();
</script>
the expected data is numbers for each var,
kindly share your knowledge
Here are a solution based on How do I pass variables and data from PHP to JavaScript? and on Pass a PHP array to a JavaScript function
<?php
// define/retrieve variables $Grammar, $Listening…
<script>
var gra = <?php echo json_encode($Grammar);?>;
var lis = <?php echo json_encode($Listening);?>;
…
var options {
…
series: [{
data: [gra, lis,…]
}],
…
Related
Got a column called ChartData in database with a string value of 4,11,25,36,50. Trying to assign this value to a hidden variable so JS can read the value of this and put this value in the data option using high charts. I have console.log the variable and looks like its appearing as a string rather than an array when being parsed across the server side to the client side.
C# code
string str = reader["ChartData"].ToString();
string[] strList = str.Split(','); //seperate the hobbies by comma
// convert it in json
dataStr = JsonConvert.SerializeObject(strList, Formatting.None);
hiddenvariable.Value = dataStr;
JS code:
function CreateBoxPlot() {
var hv = $('#hiddenvariable').val();
alert(hv); //["40","61","65","74","77"]
var chart;
var titleText = 'Test Chart Title';
var subTitleText = 'Test Chart Subtitle';
var type = 'boxplot';
var data = hv;
console.log(data); //["40","61","65","74","77"]
$(function () {
$('#container').highcharts({
chart: { type: type, inverted: true },
title: { text: titleText },
subtitle: { text: subTitleText },
legend: { enabled: false },
tooltip: {
shared: true,
crosshairs: true
},
plotOptions: {
series: {
pointWidth: 50
}
},
xAxis: {
visible: false
},
yAxis: {
visible: true,
title: {
text: 'Values'
},
plotLines: [{
value: 80,
color: 'red',
width: 2
}]
}
});
chart = $('#container').highcharts();
chart.addSeries({ data: data });
});
}
However when i hardcode data to the below value this works. How do i format this correctly when its parsed over to the JS side:
var data = [[40,61,65,74,77]]
You have to convert the string '["40","61","65","74","77"]' to js array with numbers. To make it work on each browser you can follow this approach:
Parse the string to js array using JSON.parse()
Loop through the created array and convert each element to number:
var json = '["40","61","65","74","77"]',
dataString = JSON.parse(json),
data = [],
i;
for (i = 0; i < dataString.length; i++) {
data[i] = +dataString[i];
}
Code:
$(function() {
var json = '["40","61","65","74","77"]',
dataString = JSON.parse(json),
data = [],
i;
for (i = 0; i < dataString.length; i++) {
data[i] = +dataString[i];
}
$('#container').highcharts({
chart: {
inverted: true
},
legend: {
enabled: false
},
tooltip: {
shared: true,
crosshairs: true
},
plotOptions: {
series: {
pointWidth: 50
}
},
xAxis: {
visible: false
},
yAxis: {
visible: true,
title: {
text: 'Values'
},
plotLines: [{
value: 80,
color: 'red',
width: 2
}]
}
});
chart = $('#container').highcharts();
chart.addSeries({
data: data
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="container"></div>
Demo:
https://jsfiddle.net/BlackLabel/ay1xmgoc/
Taking reference from the comments, add this to your code and then try.
var data = hv.map(function (element) {
return +element;
});
Here I am using highchart with codeigniter. I got highchart record with graph but I want record comes from mysql database field of "zreadactivity" in tooltip. I could not get proper name in tooltip for "zreadactivity" as it contains record. So, I just want to know that where I am stuck?
Here is my code:
Controller:
public function branchwiseactivityavg()
{
$data = $this->Data->branch_wise_activities();
$category = array();
$category['name'] = 'EndDate';
$series1 = array();
$series1['name'] = 'TotalValue';
$series2 = array();
$series2['name'] = 'zreadactivity';
foreach ($data as $row)
{
$category['data'][] = $row->EndDate;
$series1['data'][] = $row->TotalValue;
$series2['data'][] = $row->zreadactivity;
}
$result = array();
array_push($result,$category);
array_push($result,$series1);
array_push($result,$series2);
print json_encode($result, JSON_NUMERIC_CHECK);
}
Javascript:
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container5',
type: 'column',
marginRight: 130,
marginBottom: 25,
zoomType: 'x'
},
title: {
text: 'Branch wise activities Last 30 Days',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories : []
},
yAxis: {
title: {
text: 'TotalValue'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip:
{
formatter: function() { return ' ' +
'EndDate: ' + this.x + '<br />' +
'TotalValue: ' + this.y + '<br />' +
'zreadactivity: ' + this.series.name;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
};
$.getJSON("branchwiseactivityavg", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
chart = new Highcharts.Chart(options);
});
});
</script>
zreadactivity table:
zreadacivity
---------------
Refund
Exchange
Voids
Cancel
Discount
Price Overwrite
One way is to create JSON where for series' data each point is defined as an array like:
[value_from_TotalValue, value_from_zreadactivity]
and set keys for series like:
series: [{keys: ['y','zreadactivity']}]
and in tooltip's formatter use this.point.zreadactivity to access zreadactivity.
Other option is to build this structure for series in JavaScript after getting JSON data.
Example with keys: http://jsfiddle.net/yhx2dp2g/
Example without keys: http://jsfiddle.net/yhx2dp2g/1/
I'm plotting Csv column data in highcharts. Instead of the:
$.get('5.csv', function(data)
I want input a local desktop Csv file using:
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
My current Javascript code is below :
var options = {
chart: {
renderTo: 'container',
defaultSeriesType: 'line'
},
title: {
text: 'Test'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Units',
}
},
series: []
};
// $.get('5.csv', function(data) {
var file = event.target.file;
var reader = new FileReader();
var txt=reader.readAsText(file);
var lines = txt.split('\n');
var c = [], d = [];
$.each(lines, function(lineNo, line) {
if(lineNo > 0 ){
var items = line.split(',');
var strTemp = items[0];
c = [parseFloat(items[0]), parseFloat(items[1])];
d.push(c);
console.log(c);
}
});
options.xAxis.categories = c;
options.series = [{
data: d
}];
chart = new Highcharts.Chart(options);
});
How would I go about doing this ? I want to upload a Csv file from a local desktop machine. How do I link the File Reader upload of the file to highcharts to plot, instead of using the $.get(5.csv', function(data) { ? Or am I better using jquery-csv (https://github.com/evanplaice/jquery-csv). I know there are browser security issues. My file is a 3 column Csv with a one line header, column 1 is the x-axis, 2 is the y-axis, 3 will be the error bar, which I haven't yet implemented:
Q,I,E
0.009,2.40E-01,5.67E-02
0.011,2.13E-01,3.83E-02
0.013,2.82E-01,2.28E-02
etc ....
This works now upload by File API
function processFiles(files) {
var chart;
options = {
chart: {
zoomType: 'x',
renderTo: 'container',
type: 'line',
zoomType: 'x'
},
title: {
text: ''
},
subtitle: {
text: ''
},
xAxis: {
type: 'linear',
minorTickInterval: 0.1,
title: {
text: 'Q'}
},
yAxis: {
type: 'linear',
minorTickInterval: 0.1,
title: {
text: 'I(ntensity)'
},
},
tooltip: {
shared: true
},
legend: {
enabled: true
},
plotOptions: {
area: {
fillColor: {
linearGradient: [0, 0, 0, 300],
stops: [
[0, Highcharts.getOptions().colors[0]],
[0, 'rgba(2,0,0,0)']
]
},
lineWidth: 1,
marker: {
enabled: false,
states: {
hover: {
enabled: true,
radius: 5
}
}
},
shadow: false,
states: {
hover: {
lineWidth: 1
}
}
}
},
series: [{
name: 'Series'}]
};
var file = files[0]
var reader = new FileReader();
reader.onload = function (e) {
str = e.target.result;
var lines = str.split("\n");
var c = [], d = [], er = [];
$.each(lines, function(lineNo, line) {
if(lineNo > 0 ){
var items = line.split(',');
var strTemp = items[0];
er = parseFloat(items[2])
a = parseFloat(items[0])
b = parseFloat(items[1])
min = (b - (er/2))
max = b + ((er/2))
c = [a , b];
var q = [], e = [];
q = [min, max]
e.push(q);
d.push(c);
console.log(c);
console.log(q);
}
});
options.xAxis.categories = c.name;
lineWidth: 1
options.series = [{
data: d,
type: 'scatter'
}, {
name: 'standard deviation',
type: 'errorbar',
color: 'black',
data : e }
];
$("#Linear").click(function(){
$('#container').highcharts().yAxis[0].update({ type: 'linear'});
});
$("#Log").click(function(){
$('#container').highcharts().yAxis[0].update({ type: 'logarithmic'});
});
$("#Guinier").click(function(){
$('#container').highcharts().yAxis[0].update({ data: Math.log(d)});
options.xAxis.categories = c.name;
lineWidth: 1
options.series = [{
data: d
}]
});
chart = new Highcharts.Chart(options);
}
reader.readAsText(file)
var output = document.getElementById("fileOutput")
};
Due to security reasons you can't load a file directly on the client-side
To do this you need to use the HTML5 File API which will give the user a file dialog to select the file.
If you plan to use jquery-csv here's an example that demonstrates how to do that.
File Handling Demo
I'm biased but I say use jquery-csv to parse the data, trying to write a CSV parser comes with a lot of nasty edge cases.
Source: I'm the author of jquery-csv
As an alternative, if jquery-csv doesn't meet your needs, PapaParse is very good too.
I want to put dynamic information into my php page and keep my global option to an external JS files but "option" seem undefined:
External file:
$(function () {
var options = {
chart: {
rendedTo: 'barchart',
type: 'column',
width: 765
},
xAxis: {
labels: {
rotation: -45,
align: 'right'
}
},
yAxis: {
min: 0,
title: {
text: 'Nombre de sous-titres postés ce mois'
}
},
legend: {
enabled: false
},
tooltip: {
formatter: function() {
var s = (this.y > 1) ? 's' : '';
return '<b>'+ this.x +'</b><br/>'+
this.y+' sous-titre'+s+' posté'+s;
}
},
series: [{
name: 'Nombre d\'upload'
}]
}
});
Then I put the building lines on my head tag:
<script type="text/javascript">
$(document).ready(function(){
$.getJSON('include/ajax/statistiquesMembreMensuel.json.php?id=1', function(data) {
options.xAxis.categories = data[0];
options.series[0].data = data[0];
options.chart.title = "Nombre d\'upload mensuel effectués par le membre '.stripslashes($row['pseudo']).'";
var chart = new Highcharts.Chart(options);
});
});
</script>
I need to put the how can I send the $_GET['id'] information to the getJSON url if i put it into the .js file ?
How can I edit the chart title after the chart has been loaded?
1) Remove var to create global variable, or better, remove $(function () { ... }); which wraps options.
2) To set title, see this.
Thought I'd ask for a hand in this, am currently trying to code up a highcharts javascript file to display some data I have. I have been able to display the correct number of data sets, and on the correct graphs (they go into a time or proc graph) but I have an issue where ALL the graphs are using the same name & data, regardless of which graph they are on as well. Even though when i do an alert on where they are being assigned to their object arrays, they are all individual. Really unsure of what is happening.
where an Obj is:
{
name: SERIES_NAME,
data: SERIES_DATA,
}
The output graphs, instead of having the data as follows:
Graph Data: { Obj1, Obj2, Obj3...ObjN }, Showing multiple individual series.
I have:
Graph Data: { ObjN, ObjN, ObjN...ObjN },
They are all just ObjN. Even across the two graphs. All the data/names are the same.
Also all of this code is called from within a php $(document).ready(function())
function create_highchart(TIER,ARRAYS_STRING) {
var chart;
timestamp=document.getElementById("TIMESTAMP").value;
var graph_dir = "graphs/capsim/"+timestamp+"/";
var glue_outer = "___";
var glue_inner = ":#:";
var glue_csv="^";
var i = 0;
var j = 0;
var tier_names=[];
var WL_names = [];
var CSV_data=[];
var CSVs = [];
var CSV_det=[];
var out_arrays=[];
var time_ids = ['queue','util','arrival','thruput'];
out_arrays = ARRAYS_STRING.split(glue_outer);
tier_names = out_arrays[0].split(glue_inner);
WL_names = out_arrays[1].split(glue_inner);
CSVs = out_arrays[2].split(glue_inner);
CSV_det = out_arrays[3].split(glue_inner);
WL_num = WL_names.length;
tier_names.push('Overall System');
tier_max = tier_names.length;
curr_tier_name = tier_names[TIER];
while(i<CSVs.length){
CSV_data[i]=[];
data = CSVs[i].split(glue_csv);
CSV_data[i]=data;
i=i+1;
}
i=0;
var TMP_series = {
name: '',
data: [],
}
var TIME_SERIES_DATA=[];
var PROC_SERIES_DATA=[];
var time_count=0;
var proc_count=0;
var x = [];
var y = [];
var cat = [];
var out2 = [];
var options_time={
chart: {
renderTo: 'hc_div2',
type: 'scatter',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Highcharts Demo for Graphing',
x: -20 //center
},
subtitle: {
text: 'Graph for '+curr_tier_name,
x: -20
},
yAxis: {
title: {
text: 'Performance Metrics'
},
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
'X: '+this.x +' Y: '+ this.y
}
},
plotOptions: {
scatter: {
marker: {
radius: 2,
}
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: 10,
y: 100,
borderWidth: 0
},
series: TIME_SERIES_DATA
};
var options_proc={
chart: {
renderTo: 'hc_div1',
type: 'scatter',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Highcharts Demo for Graphing',
x: -20 //center
},
subtitle: {
text: 'Graph for '+curr_tier_name,
x: -20
},
yAxis: {
title: {
text: 'Performance Metrics'
},
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
'X: '+this.x +' Y: '+ this.y
}
},
plotOptions: {
scatter: {
marker: {
radius: 2,
}
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: 10,
y: 100,
borderWidth: 0
},
series: PROC_SERIES_DATA
};
var i=0;
if(TIER==tier_max-1){
TIER='OVR';
};
while(i<=CSV_det.length){
csv = CSV_det[i+4];
curr_data=CSV_data[(i/5)];
csv_name = CSV_det[i+1];
csv_tier = CSV_det[i+2];
csv_wl = parseFloat(CSV_det[i+3])+1;
wl_info = '';
if(CSV_det[i+3] !='NA'){
wl_info = ' Workload: '+csv_wl;
};
var j=0;
var line = '';
if(TIER==csv_tier){
TMP_series.data = [];
TMP_series.name = csv_name+wl_info;
while(j<curr_data.length){
XY=curr_data[j].split(',');
X = parseFloat(XY[0]);
Y = parseFloat(XY[1]);
TMP_series.data.push([X,Y]);
j=j+1;
}
j=0;
csv_type=csv.split('/')[3].split('_')[0];
if($.inArray(csv_type,time_ids)==-1){
PROC_SERIES_DATA[proc_count]=[];
PROC_SERIES_DATA[proc_count]=TMP_series;
proc_count=proc_count+1;
}else{
TIME_SERIES_DATA[time_count]=[];
TIME_SERIES_DATA[time_count]=TMP_series;
time_count=time_count+1;
}
}
i=i+5;
};
var chart = new Highcharts.Chart(options_proc);
var chart = new Highcharts.Chart(options_time);
}
A quick explanation on whats going on:
Initially parsing all the data into relevant bins from the arrays string
Creating the two highcharts that wil be displayed
Scanning over the CSVs to find ones that are relevant
For ones that are, reading their Data, and adding it to a TMP_series
Once all data is read, adding the TMP_series to the relevant graph data series
Any help is greatly apprecaited!
Thanks
You need to reset TMP_series to a new object each time you generate a series. Right now you are recycling the same object, and pushing references to the same object into the series arrays. Modify the last bit of your code to read like this:
if(TIER==csv_tier){
TMP_series = {
name : csv_name+wl_info,
data : []
};
while(j<curr_data.length){
XY=curr_data[j].split(',');
X = parseFloat(XY[0]);
Y = parseFloat(XY[1]);
TMP_series.data.push([X,Y]);
j=j+1;
}
j=0;
csv_type=csv.split('/')[3].split('_')[0];
if($.inArray(csv_type,time_ids)==-1){
PROC_SERIES_DATA[proc_count]=[];
PROC_SERIES_DATA[proc_count]=TMP_series;
proc_count=proc_count+1;
}else{
TIME_SERIES_DATA[time_count]=[];
TIME_SERIES_DATA[time_count]=TMP_series;
time_count=time_count+1;
}
}
Notice how at the top of the if, I create a new object with the specified properties, and assign it to the reference TMP_series. Remember, objects are passed by reference, so when you push objects into arrays, you are pushing a reference to the object, not a copy of the object.