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.
Related
I am trying to dynamically load in a number of series, depending on projects chosen by the user. I am using Laravel 5.2, PHP 5.6 and HighCharts.
I have managed to load in one JSON file, which is generated when the user selects projects. But I would like it if the JavaScript could parse the different series from the JSON file and dynamically load this into the series.
This is the code which I am using:
$(function () {
// Set up the chart
var processed_json = new Array();
$.getJSON('/uploads/test.json', function(data) {
for (i = 0; i < data.length; i++) {
processed_json.push([data[i].key, data[i].value]);
}
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column',
options3d: {
enabled: true,
alpha: 0,
beta: 0,
depth: 0,
viewDistance: 25
}
},
title: {
text: 'Grades'
},
subtitle: {
text: 'Dataset'
},
plotOptions: {
column: {
depth: 0
}
},
series: [{
name: 'Grades',
data: processed_json
}],
credits: {
enabled: false
}
});
function showValues() {
$('#alpha-value').html(chart.options.chart.options3d.alpha);
$('#beta-value').html(chart.options.chart.options3d.beta);
$('#depth-value').html(chart.options.chart.options3d.depth);
}
// Activate the sliders
$('#sliders input').on('input change', function () {
chart.options.chart.options3d[this.id] = this.value;
showValues();
chart.redraw(false);
});
showValues();
});
});
My JSON is formatted like:
[{"key":"Math","value":6},{"key":"Biology","value":"8"},{"key":"English","value":"7"},{"key":"Gym","value":"4"}]
So I would like to have more JSONs like so, in one file to be parsed in the Javascript and be loaded in into the series.
Thank you!
EDIT
thanks for your reply. I have edited my code:
$(function () {
var processed_json = new Array();
var options = {
chart: {
renderTo: 'container',
type: 'column',
options3d: {
enabled: true,
alpha: 0,
beta: 0,
depth: 0,
viewDistance: 25
}
},
title: {
text: 'Grades'
},
subtitle: {
text: 'Dataset'
},
plotOptions: {
column: {
depth: 0
}
},
series: [{
}],
credits: {
enabled: false
}
};
$.getJSON('/uploads/test.json', function(data) {
for (i = 0; i < data.length; i++) {
processed_json.push([data[i].key, data[i].value]);
}
});
options.series[0].remove();
options.series[0].setData = {
name: 'Grades',
data: processed_json
}
var chart = new Highcharts.Chart(options);
chart.redraw(true);
function showValues() {
$('#alpha-value').html(chart.options.chart.options3d.alpha);
$('#beta-value').html(chart.options.chart.options3d.beta);
$('#depth-value').html(chart.options.chart.options3d.depth);
}
// Activate the sliders
$('#sliders input').on('input change', function () {
chart.options.chart.options3d[this.id] = this.value;
showValues();
chart.redraw(false);
});
showValues();
});
But nothing is displayed anymore and the following error is given
TypeError: options.series[0].remove is not a function
I have also tried
var chart = new Highcharts.Chart(options);
chart.series[0].remove();
chart.series[0].setData = {
name: 'Grades',
data: processed_json
}
chart.redraw(true);
But this gives:
TypeError: Cannot set property 'setData' of undefined
I think highcharts has a method chart.addSeries for adding a new series. If you want to replace the current series with a new series, you can try removing first the current series using chart.series[0].remove( ) then add the new series with chart.addSeries. The parameter for the chart.addSeries can be an object like your
{
name: 'Grades',
data: processed_json
}
Then, define method with load data.. example:
function(chart) {
$.each(chart.series, function(i, v){
chart.series[i].remove(true);
});
chart.addSeries({your_data}, true);
}
check http://api.highcharts.com/highcharts/Chart.addSeries/Chart.addSeries
In my webapp, i use 10 of 15 types of graphs highchart and all dynamically load and work fine :) Highcharts is awesome.
I am trying to plot a chart which will read a data from csv file which is appending on every minute with latest data as per below format.
The chart will continue reading data from csv file and show the graph on every second wise. Can you please help me on this? I want to show the exact time which are coming from file should be show on graph.
CSV format..
time,count
18:01:00,3
18:01:01,4
....
$(document).ready(function () {
var csv = [],
x;
Highcharts.setOptions({
global: {
useUTC: false
}
});
var data = 'time,count\n18:01:00,3\n18:01:01,4';
//$.get('data.csv', function(data) {
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
if(lineNo > 0) {
var items = line.split(',');
useUTC: false;
x = items[0].split(':');
csv.push([Date.UTC(2015,1,1,x[0],x[1],x[2]), parseFloat(items[1])]);
}
});
console.log(csv);
$('#container').highcharts({
chart: {
renderTo: 'container',
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
useUTC: false,
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function () {
var l = series.data.length - 1,
lastX = series.data[l].x;
$.get('data.csv', function(data) {
var lines = data.split('\n'),
len = lines.length,
items = lines[len - 1].split(','),
x = items[0].split(':'),
y = parseFloat(items[1]);
useUTC: false;
x = Date.UTC(2015,1,1,x[0],x[1],x[2]);
if(x !== lastX) {
series.addPoint([x, y], true, true);
}
});
}, 1000); //refresh each 1 second
}
}
},
title: {
text: 'TPS Data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 3,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%H:%M:%S', this.x) + '<br/>' +
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Count',
data: csv
}]
});
//});
});
div {
min-width: 50px;
height: 200px;
margin: 0 auto;
}
<script type="text/javascript" src="http://code.jquery.com/jquery-1.12.0.js"></script>
<script type="text/javascript" src="http://code.highcharts.com/highcharts.js"></script>
<div id="container" style=""></div>
Note In the snippet I was replace the ajax function $.get with hardcoded data so it will show the result but the question is about the ajax way.
I'm new in Laravel, so I'm still facing problems whenever I try to add js functions to my code.
I need to add a highchart to my laravel project. As a beginning, I just copied the code of one of the charts available on highcharts.com and pasted it in the main view, but nothing is being displayed.
When I added the same code to a normal html file, the graph was displayed normally.
Here's my javascript code
<script 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">
$(function () {
$(document).ready(function () {
Highcharts.setOptions({
global: {
useUTC: false
}
});
$('#container').highcharts({
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
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: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
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 += 1) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
}())
}]
});
});
});
</script>
and the html code
<div id="container" style="width:100%; height:400px;"></div>
Any suggestions how to display the graph?
Thanks in advance.
I think the problem is with the syntax you are creating the chart with: $('#container').highcharts...
It seems highcharts function is not defined using laravel.
There is another way that you can try:
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
...
},
...
});
I ran into a problem that I do not manage to solve. Indeed I have JS with apex variable in it and I want to rerender this block in the way to get the fresh values back. I am using the outputpanel but unfortunatly no rerender happen. My code is like below
<apex:commandButton value="button" id="theButton" action="{!setDataSet}" oncomplete="refreshMyChart()" rerender="jstorerender"/>
<apex:outputpanel id="jstorerender">
<script type="text/javascript" >
$j = jQuery.noConflict();
var innerVar = '{!innerString}';
var covVar = '{!coverageAsCategorie}';
console.log("want to refreshINIT"+innerVar+covVar);
</script>
</apex:outputpanel>
The refresh my chart function is a little bit complex so I put it in another block as far as I do not think that this is the source of the problem because the rerender should happen befor the oncomplete:
<script type="text/javascript">
function refreshMyChart(){
console.log("want to refreshINIT2"+innerVar+covVar);
var chart;
var colors = Highcharts.getOptions().colors;
var categories = ['{!coverageAsCategorie}'];
var name = 'Browser brands';
var data = ['{!innerString}'];
function setChart(options) {
chart.series[0].remove(false);
chart.addSeries({
type: options.type,
name: options.name,
data: options.data,
color: options.color || 'white'
}, false);
chart.xAxis[0].setCategories(options.categories, false);
chart.redraw();
};
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
inverted:true
},
title: {
text: 'Browser market share, April, 2011'
},
subtitle: {
text: 'Click the columns to view versions. Click again to view brands.'
},
xAxis: {
categories: categories
},
yAxis: {
title: {
text: 'Total percent market share'
}
},
plotOptions: {
series: {
cursor: 'pointer',
point: {
events: {
click: function() {
var drilldown = this.drilldown;
var options;
if (drilldown) { // drill down
options = {
'name': drilldown.name,
'categories': drilldown.categories,
'data': drilldown.data,
'color': drilldown.color,
'type': 'columnrange',
};
} else { // restore
options = {
'name': name,
'categories': categories,
'data': data,
'type': 'pie'
};
}
setChart(options);
}
}
},
dataLabels: {
enabled: true,
color: colors[0],
style: {
fontWeight: 'bold'
},
formatter: function() {
return this.y +'%';
}
}
}
},
tooltip: {
formatter: function() {
var point = this.point,
s = this.x +':<b>'+ this.y +'% market share</b><br/>';
if (point.drilldown) {
s += 'Click to view '+ point.category +' versions';
} else {
s += 'Click to return to browser brands';
}
return s;
}
},
series: [{
type: 'pie',
name: name,
data: data,
color: 'white'
}],
exporting: {
enabled: false
}
});
};</script>
Anyway what happen when I click on my button? :
The console.log inside my refresh function appear (then I guess that oncomplete event has been triggered)
The console.log inside my outputpanel block IS NOT display. Then I think that there is an issue with the rerender.Plus the console.log IS diplay when the page load so I do not think that here is any issue with the code...
Moreover there are not JS error triggered. Then I really do not the why the rerender do not wanna operate.
Any idea of what happens here?
Thx guys :)
Invoke refreshMyCart from inside the re rendered ouputpanel.
Hello I have a problem with HighCharts under IE < 9.
Internet explorer HighCharts screenshot
HighCharts works fine in other browsers screenshot
As you can see the chart is rendered in IE and in Chrome but..
The lines are rendered just in the Chrome, the data has to be there also for IE because legend box is there (Best Bid, Qualification Value ...)
The code(By the way it's erb template so I load data from Rails):
<script type="text/javascript">
"use strict";
var chart;
// assign data for current and qualification values
var qualificationTranslation = "<%= t(:qualification_value_nobr) %>";
var currentTranslation = "<%= t(:event_current_value) %>";
var qualificationValue = <%= #lot.qualification_value %>
var currentValue = <%= #lot.current_value %>
jQuery(document).ready(function() {
var parseChartData = function(data) {
var chartData = [];
jQuery.each(data, function(index, value) {
chartData.push({
x: Date.parse(value.x),
y: parseFloat(value.y),
formated_value: value.formated_value
});
});
return chartData;
};
var dataForChart = parseChartData(<%= raw data[:chart_data].to_json %>);
chart = new Highcharts.Chart({
chart: {
renderTo: 'chart',
type: 'line',
zoomType: 'x',
marginRight: 25
},
credits: {
enabled: false
},
title: {
text: "<%= t(:total_difference_progression_chart) %>",
x: -20 //center
},
xAxis: {
type: 'datetime',
labels: {
formatter: function() {
return Highcharts.dateFormat('%I:%M %p', this.value)
}
}
},
yAxis: {
title: {
text: "<%= t(:bid_value_price_per_uom_x_quantity, :symbol => #lot.event.currency.symbol) %>"
}
},
tooltip: {
formatter: function() {
var serieName = this.point.series.name;
// Don't show tooltip when you hover over qualification or current price
if(serieName == qualificationTranslation || serieName == currentTranslation) {
return false;
} else {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.dateFormat('%d %b %I:%M:%S %p', this.x) +
'<br/><b>'+ this.point.formated_value + '</b>';
}
}
},
legend: {
backgroundColor: '#FFFFFF',
verticalAlign: 'top',
y: 20,
shadow: true
},
plotOptions: {
series: {
step: true
}
},
series: [{
name: "<%= t(:best_bid) %>",
data: dataForChart
}]
});
// This function will add the current price and qualification price lines
var addOrUpdateSerie = function(name, value, serie) {
var data = []
data.push([chart.xAxis[0].min, value])
data.push([chart.xAxis[0].max, value])
var options = {
name: name,
type: 'spline',
dashStyle: 'shortdot',
marker: {enabled: false},
data: data
}
if(!serie) {
chart.addSeries(options);
} else {
serie.setData(data)
}
};
addOrUpdateSerie(qualificationTranslation, qualificationValue);
addOrUpdateSerie(currentTranslation, currentValue);
socket = io.connect(
ioServerAddr + '/charts',
{query: "lot_id=<%= #lot.id %>", secure: isProduction}
)
socket.on('connect', function() {
socket.emit('join', 'host_difference_progression_event_chart');
});
socket.on('<%= #lot.id %>/host_difference_progression_event_chart', function(data) {
// Add data to series
chart.series[0].setData(parseChartData(data.chart_data))
//Update hirizontal values
addOrUpdateSerie(qualificationTranslation, qualificationValue, chart.series[1])
addOrUpdateSerie(currentTranslation, currentValue, chart.series[2])
chart.redraw();
});
});
</script>
EDIT: It raises NO error
SOLVED:
The problem was with Date.parse() because IE uses other format.
http://www.ruby-doc.org/stdlib-1.9.3/libdoc/date/rdoc/Date.html#method-i-httpdate solved the problem
SOLVED: The problem was with Date.parse() because IE uses other format. http://www.ruby-doc.org/stdlib-1.9.3/libdoc/date/rdoc/Date.html#method-i-httpdate solved the problem
I find a solution to render Highcharts on IE7, IE8 and more !
Add this :
<meta http-equiv="X-UA-Compatible" content="chrome=IE7">
I don't know why this works but it works :)