Set Xaxis from Json data in Highchart - php

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

Related

How to correct index and current date

I have the following error with this highcharts chart library.
I need to update the date to the current one and that the date of the corresponding day appears in the index.
just change from Highcharts.chart to Highcharts.stockChart. (Attached image)
enter image description here
enter image description here
from here the data and graph are brought
function datagrafico(base_url){
$.ajax({
url: base_url + "index.php/Admin/getDataDias",
type:"POST",
dataType:"json",
success:function(data){
var dias = new Array();
var montos = new Array();
$.each(data,function(key, value){
dias.push(value.fecha_actualizacion);
valor = Number(value.monto);
montos.push(valor);
});
graficar(dias,montos);
}
});
}
function graficar(dias, montos){
Highcharts.stockChart('grafico', {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Monto acumulado por ventas diarias'
},
subtitle: {
text: ''
},
xAxis: {
categories: dias,
crosshair: true
},
yAxis: {
min: 0,
title: {
text: 'Monto Acumulado (Colombiano)'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">Monto: </td>' +
'<td style="padding:0"><b>{point.y} Colombiano</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0,
borderWidth: 0
},
series:{
dataLabels:{
enabled:true,
formatter:function(){
return Highcharts.numberFormat(this.y)
}
}
}
},
rangeSelector: {
inputPosition: {
align: 'right',
x: 0,
y: 0
},
},
series: [{
name: 'dias',
data: montos
}]
});
controller:
public function getDataDias(){
$resultados = $this->model_venta->montos();
echo json_encode($resultados);
}
and model:
public function montos(){
$this->db->select("fecha_actualizacion, SUM(total) as monto");
$this->db->from("venta");
$this->db->where("pago_id","2");
$this->db->where("estado","1");
$this->db->group_by('DATE(fecha_actualizacion)');
$this->db->order_by('DATE(fecha_actualizacion)');
$resultados = $this->db->get();
return $resultados->result();
}
In your example you change Highcharts to Higcharts Stock, they are similar but building charts from other API. Please have a look at the Stock documentation they, do not have categories options inside xAxis.
The millisecond format of data is standard in the Highcharts Stock axis, you need to change data format to put it in the chart.
series: [{
type: 'column',
data: [
[1592314200000, 165428800],
[1592400600000, 114406400],
[1592487000000, 96820400],
[1592573400000, 264476000],
[1592832600000, 135445200],
[1592919000000, 212155600]
],
}]
Under are Highchart and Higcharts Stock examples to compare of building.
Highchart Demo: https://jsfiddle.net/BlackLabel/sw3qr5p9/
Highchart Stock Demo: https://jsfiddle.net/BlackLabel/drnup1tx/

Hightchart with ajax request

Good day, i'm trying to create a chart. The chart value is from ajax return.
I got this data
"tgl":["2016-07-12 00:00:00.000","2016-07-01 00:00:00.000"],"total":[1283947,1234618514]}
and here it's my js for handle hightchart
xAxis: {
categories: [
$.each(data.tgl, function(k, v) {
data.tgl
})
]
},
series: [{
name: 'Outlet' +$("#outlet").val(),
data: [
$.each(data.total, function(k, v) {
data.total
})
]
}]
i don't know how to foreach ajax so i follow this link jQuery loop over JSON result from AJAX Success?
and here is my php
function getajax()
{
extract(populateform());
$explode = explode('-',$date_search);
$start_date = inggris_date($explode[0]);
$end_date = inggris_date($explode[1]);
$hasil = $this->modelmodel->showdata("select tanggal,(cash + cc + dc + flash + piutang + reject + disc50)
total from transaksi
where tanggal between '$start_date' and '$end_date' and
outlet = '".$outlets."' order by tanggal desc");
$data = array();
foreach($hasil as $hsl)
{
$data['tgl'][] = $hsl->tanggal;
$data['total'][] = $hsl->total;
}
echo json_encode($data);
}
The result from my script above is like this.
as you can see from my data above. My chart not showing the right value. It should be like this 2016-07-12 00:00:00.000 => 1283947 and 2016-07-01 00:00:00.000 => 1234618514
My lates fiddle https://jsfiddle.net/oyrogu9v/1/
you should have 2 values in the series: time and total.
series: [{
name: 'Winter 2012-2013',
data: [
[Date.UTC(1970, 9, 21), 0],
[Date.UTC(1970, 10, 4), 0.28],
..................
you can see here a sample:
Highchart sample timeserie
please try this code:
$(document).ready(function() {
$("#test").click(function() {
var $btn = $(this);
$btn.button('loading');
$.ajax({
url: '<?=base_url();?>graph/getajax',
data: {outlets:$("#outlet").val(),date_search:$("#reservation").val()},
type: 'POST',
dataType: 'JSON',
success: function(data) {
var res= [];
$.each(data, function(k, v) {
res.push([new Date(data[k].tanggal).getTime(), data[k].total])});
$('#container').highcharts({
title: {
text: '',
x: -20 //center
},
subtitle: {
text: 'Omset ' + $("#outlet").val(),
x: -20
},
xAxis: {
type: 'datetime'
},
yAxis: {
title: {
text: 'Rupiah (Rp.)'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
valueSuffix: ' Rupiah'
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: [{
name: 'Outlet '+ $("#outlet").val(),
data:res
}]
});
});
setTimeout(function () {
$btn.button('reset');
}, 1000);
});
});
here you can see the results: https://jsfiddle.net/mb89apxr/

how can I modify my function via ajax?

well, to start I used to make my JSON function, but when I wanted add data I couldn't. So How can I my json function ? i'm using getJSON but I can't add data like ajax then how could I change it to ajax style. it's for hightchart
$(function() {
var processed_json = new Array();
$.getJSON('../controllers/chart_controller.php', function(data){
for (i = 0; i < data.length; i++){
processed_json.push([data[i].key,data[i].value]);
}
//draw chart
$('#salesChart').highcharts({
chart: {
type: "column"
},
title: {
text: "Best selling product"
},
xAxis: {
type: 'category',
allowDecimals: false,
title: {
text: ""
}
},
yAxis: {
title: {
text: "Scores"
}
},
series: [{
name: 'Sales',
data: processed_json
}]
});
});
});

highchart Dynamically updated data

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/

Bars does not show up when loading JSON encoded data from PHP in Highcharts

I am loading data stored in a MySQL Database.
The chart doesn't show up on the webpage, but it doesn't show any other warning.
My PHP webpage returns a JSON encoded header with the following information:
["John Doe","2","Jane Doe","3"]
The script that loads the information is the following:
var chart;
function requestData() {
$.ajax({
url:'includes/bin/get_leaders.php',
success: function(point) {
alert(point);
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is longer than 20
chart.series[0].addPoint(point, true, shift);
},
cache: false
});
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'bar',
events: {load: requestData}
},
title: {
text: 'Top Agents'
},
xAxis: {
type: 'int',
title: {text: null}
},
yAxis: {
min: 0,
title: { text: 'Sales this Week', align: 'low'}
},
tooltip: {
formatter: function() {
return ''+ this.series.name +': '+ this.y +' sales';
}
},
plotOptions: {
bar: {
dataLabels: {
enabled: true
}
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -100,
y: 100,
floating: true,
borderWidth: 0,
backgroundColor: '#FFFFFF',
shadow: false
},
credits: {
enabled: false
},
series: [{
name: 'Sales' }]
});
});
});
Any clue what's going on?
Thank you!
Looks like you are passing in a ["string", "number", "string", "number"].
What you want is {2, 3} for your series and then for your xAxis to use a category list of {"John Doe", "Jane Doe"}.

Categories