i want to set up highcharts.
i made a simple random number in this url
http://echocephe.com/new/custom_number.php
i want to use these random datas on Dynamically updated data charts
this is code can you help me to solve this problem thanks.
<script type="text/javascript">
$(function () {
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart;
$('#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++) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
})()
}]
});
});
});
</script>
maybe its better to check highchart forums
here is the answer
http://www.highcharts.com/docs/working-with-data/preprocessing-live-data/
Related
I have json data like this:
and I want to display the above date data as x-axis on my chart:
$(document).ready(function () {
getAjaxData(1);
var val = location.search.split('balai=')[1]
getAjaxData(val);
function getAjaxData(balai){
$.getJSON('src/json/proyek/progress-fisik.php', {balai: balai}, function(progressFisik) {
var chart1 = new Highcharts.Chart('progress_fisik', {
chart: {
renderTo: 'progress_fisik',
type: 'column',
},
title: {
text: ''
},
subtitle: {
text: ''
},
yAxis: {
min: 0,
max: 100,
tickInterval: 20,
allowDecimals: false,
title: {
text: ''
},
},
xAxis: {
type: 'datetime',
labels: {
formatter: function ( ){
return Highcharts.dateFormat('%d-%m-%Y');
},
},
},
tooltip:{
formatter: function() {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.numberFormat(this.y, 2) +' %';
},
},
plotOptions: {
column: {
dataLabels: {
enabled: true,
format: '{point.y:,.2f}'+'%',
}
},
},
series:progressFisik,
});
});
}
});
I've spent a lot of time trying to solve this problem, but haven't gotten any results until now.
I hope someone is kind enough to help me on how I can improve my code above. any help I really appreciate. thanks.
You need to adapt your data to the format required by Highcharts. For example:
const series = progressFisik.map(dataEl => ({
name: dataEl.name,
data: dataEl.data.map((y, index) => [
new Date(dataEl.date[index]).getTime(),
y
])
}));
Live demo: http://jsfiddle.net/BlackLabel/Lhmw8p5f/
API Reference: https://api.highcharts.com/highcharts/series.line.data
am working in PHP. i am using High Chart , dynamically taking data from DB. Now i want to show data between certain date range. Data between certain date range is successfully fetched from DB but now how to refresh the Chart ??
JS Code :
`
function piechart() {
var date_from = $("#date_from").val();
var date_to = $("#date_to").val();
var dataString = 'date_from=' + date_from + '&date_to=' + date_to;
$.ajax({
type: "GET",
url: "pages/dashboard/chart_data.php",
data: dataString,
cache: false,
success: function(html) {
}
});
return false;
}
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Current Year Sales Report'
},
tooltip: {
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';
}
}
}
},
series: [{
type: 'pie',
name: 'Sales (Rupees)',
data: []
}]
}
$.getJSON("chart_data.php", function(json) {
options.series[0].data = json;
chart = new Highcharts.Chart(options);
});
});
`
and chart_data.php
`
if($date_from !='' AND $date_to !='')
{
$where = "tran_date >='$date_from' AND tran_date <= '$date_to'";
echo $db->piechart($where);
}
else
echo $db->piechart();
?>
`
Any help will be highly appreciated.
It looks like it is JavaScript question.
You should move your code inside
`$(document).ready(function() {`
block into the function and execute it each time your date range fields are changed or then document is loaded first time.
I m trying to figure it out that is it possible to make the json data fetched dynamically from a database with the help of php and mysql and can be plotted with highcharts that too dynamic auto updating? Any help would be appreciated.
following the code i have tried and is not working properly and want to implement to the the website for 10 lines.
<HTML>
<HEAD>
<TITLE>highchart example</TITLE>
<script type="text/javascript"src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script type="text/javascript">
var chart;
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is
// longer than 2
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData1, 1000);
},
cache: false,
});
}
function requestData1() {
$.ajax({
url: 'live-server-data.php',
success: function(point) {
var series2 = chart.series[1],
shift = series2.data.length > 20; // shift if the series is
// longer than 20
// add the point
chart.series[1].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false,
});
}
$(function () {
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis:
{
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: '',
margin: 80
}
},
series: [
{
name: 'Random data',
data: []
},
{
name: ' hahaha',
data: []
}
],
});
});
});
</script>
</HEAD>
<BODY>
<div id="container"
style="min-width: 728px; height: 400px; margin: 0 auto"></div>
</BODY>
</HTML>
*** the live-server-data.php is as followed:
<?php
// Set the JSON header
header("Content-type: text/json");
// The x value is the current JavaScript time, which is the Unix time multiplied
// by 1000.
$x = time() * 1000;
// The y value is a random number
$y = rand(48,52);
// Create a PHP array and echo it as JSON
$ret = array($x, $y);
echo json_encode($ret);
?>
You can try with
var options = {
chart: {
renderTo: 'chart',
},
credits: {
enabled: false
},
title: {
text: 'Impression/Click Overview',
x: -20
},
xAxis: {
categories: [{}]
},
tooltip: {
formatter: function() {
var s = '<b>'+ this.x +'</b>';
$.each(this.points, function(i, point) {
s += '<br/>'+point.series.name+': '+point.y;
});
return s;
},
shared: true
},
series: [{},{}]
};
$.ajax({
url: "json.php",
data: 'show=impression',
type:'post',
dataType: "json",
success: function(data){
options.xAxis.categories = data.categories;
options.series[0].name = 'Impression';
options.series[0].data = data.impression;
options.series[1].name = 'Click';
options.series[1].data = data.clicks;
var chart = new Highcharts.Chart(options);
}
});
The highcharts website has some useful articles about working with dynamic data. That is probably the best place to start.
http://www.highcharts.com/docs/working-with-data/preprocessing-live-data
http://www.highcharts.com/docs/working-with-data/preprocessing-data-from-a-database
Try something out, and if you have trouble, come back here with a more specific question showing what you have tried. As it stands, your question is too broad, and will probably get closed.
An ajax request for updating data looks something like:
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is // longer than 20
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
I have a problem when I pass parameters with json_encode because I need to pass two arrays from php to javascript. My code run ok if i don't put the arrays
This is my javascript charts code:
function ChangeChartType(chart, series, newType) {
newType = newType.toLowerCase();
for (var i = 0; i < series.length; i++) {
var srs = series[0];
try {
srs.chart.addSeries({
type: newType,
stack: srs.stack,
yaxis: srs.yaxis,
name: srs.name,
color: srs.color,
data: srs.options.data
},
false);
series[0].remove();
} catch (e) {
}
}
}
// Two charts definition
var chart1, chart2;
// Una vez que el DOM (documento) ha acabado de cargar
$(document).ready(function() {
// First chart initialization
chart1 = new Highcharts.Chart({
chart: {
renderTo: 'chart_1',
type: 'column',
height: 350,
},
title: {
text: "<?php echo $titulo; ?>"
},
xAxis: {
categories: ['Processing.js', 'Impact.js', 'Other', 'Ease.js', 'Box2D.js', 'WebGL', 'DOM', 'CSS', 'Canvas', 'Javascript']
},
yAxis: {
title: {
text: 'Meses'
}
},
},function(chart){
//var i = 0;
for(i=0; i<3; i++) {
chart.addSeries({
data: [32, 43, 42],
index: 0,
zIndex:1
});
}
});
// Second chart initialization (pie chart)
chart2 = new Highcharts.Chart({
chart: {
renderTo: 'chart_2',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
},
title: {
text: "<?php echo $titulo; ?>"
},
tooltip: {
formatter: function() {
var s;
if (this.point.name) { // the pie chart
s = ''+
this.point.name +': '+ this.y + ' totales';
} else {
s = ''+
this.x +': '+ this.y + ' totales';
}
return s;
}
//pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
format: '<b>{point.name}</b>: {point.percentage:.1f} %'
},
showInLegend: true
}
},
series: [{
type: 'pie',
name: 'Resultado',
data: [<?php echo $resultado ?>]
}]
});
// Switchers (of the Chart1 type) - onclick handler
$('.switcher').click(function () {
var newType = $(this).attr('name');
ChangeChartType(chart1, chart1.series, newType);
});
});
I open both charts with a dialog window
$(function() {
$( "#dialog1" ).dialog({
autoOpen: false,
width: 950,
height: 460,
show: {
effect: "blind",
duration: 1000
},
hide: {
effect: "blind",
duration: 1000
}
});
$( "#dialog2" ).dialog({
autoOpen: false,
width: 650,
height: 760,
show: {
effect: "blind",
duration: 1000
},
hide: {
effect: "blind",
duration: 1000
}
});
$( "#opener1" ).click(function() {
$( "#dialog1" ).dialog( "open" );
});
$( "#opener2" ).click(function() {
$( "#dialog2" ).dialog( "open" );
});
});
The problem is when i try add this arrays to add months and names instead of ['Processing.js', 'Impact.js', 'Other', 'Ease.js', 'Box2D.js', 'WebGL', 'DOM', 'CSS', 'Canvas', 'Javascript'] and default names
// Two charts definition
var chart1, chart2;
// Una vez que el DOM (documento) ha acabado de cargar
$(document).ready(function() {
var nombres = <?php echo json_encode($names); ?>; //I CAN'T SEE MY FIRST PIE CHART
var meses = <?php echo json_encode($valorX); ?>; //WHEN I INSERT BOTH VARIABLES
// First chart initialization
chart1 = new Highcharts.Chart({
chart: {
renderTo: 'chart_1',
type: 'column',
height: 350,
},
My portion of php
$valorX = array('Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre');
$names = array('Ana', 'Elena', 'Juan');
So, I don't know what i did wrong. With only these arrays declared, my second chart (Pie chart) doesn't appear. My code is under construction. Sorry my bad english, coding and Thanks you very much!!!!!!
This is my full code:
$(document).ready(function()
{
var options =
{
chart: { renderTo: 'zb' },
title: { text: 'Test' },
tooltip:
{
enabled: true,
formatter: function()
{
return '<b>' + this.x + ' ' + this.series.name + '</b><br/>' + this.y;
}
},
xAxis: { categories: [] },
yAxis: { title: { text: 'Visits Num' } },
series: [],
plotOptions:{ line: { lineWidth : 2 } }
};
var tpo;
$.ajax({url: 'utils/request2.php', success: function(data)
{
var lines = data.split('\n');
var series =
{
type: 'line',
name: 'Visits',
data: [],
marker: { enabled: true, radius : 3 }
};
var cats = [];
$.each(lines, function(lineNo, line)
{
var line_data = line.split(',');
series.data.push(parseInt(line_data[1]));
});
options.series.push(series);
var chart = new Highcharts.Chart(options);
}});
});
It calls to the request2.php file that have data (saved in UTF8 without BOM if it matters) separated with comma, 2 values per row
When I'm showing the data without the parseInt it's showing the line, but the numbers are wrong because it's string - like showing 1500 as 20
Anyone have an idea why?
Thanks alot.