refresh High chart after submitting a date range in PHP - php

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.

Related

Set Xaxis from Json data in Highchart

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

How to show multiple highcharts on selection of few parameters and dynamically load JSON data using PHP page?

I have two parameters to load dynamic json data from mysql and visualise multiple line charts on page submit.
$.ajax({
url: 'get_pubmedid.php',
type: 'get',
data: {org: org, ptype: ptype, path: path,mirna: mirna},
dataType: 'json',
success:function(response) {
var len = response.length;
for( var i = 0; i<len; i++) {
pubmed = response[i]['name'];
cell=response[i]['cell'];
alert(cell+" "+pubmed+" "+len);
var cells=encodeURIComponent(cell);
var cname="charts"+(i+1);id=i+1;var pid=i+1;
var container = cname;
var func_name = cname;
func_name = function () {
Highcharts.chart(container, {
showhighcharts(org,ptype,path,mirna,cell,cells,pid,pubmed,cname,id);
}
}
func_name()
}
}
});
function showhighcharts(org,ptype,path,mirna,cell,cells,pid,pubmed,cname,id) {
$("#"+cname).html("Wait, Loading graph...");
var options = {
chart: {
type: 'line',
renderTo: cname
},
colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4'],
credits: {
enabled: false
},
title: {
text: 'Temporal Viewer',
x: -20
},
xAxis: {categories:<?php //echo $_SESSION["cat"]; ?>,
offset:2,
title: {enabled: true,text: 'Time Point' }
},
tooltip: {
shared: true,
useHTML: true,
headerFormat: '<b>Time Point:{point.key}</b> <table style="width:200px;font-size:12px;font-weight:bold;">',
pointFormat: '<tr><td>Dosage:</td><td style="color: {series.color}">{series.name} </td></tr>' + '<tr><td>Fold Change:</td><td style="color: {series.color}">{point.y} </td></tr>',
footerFormat: '</table>',
enabled: true,
crosshairs: {
color: 'light gray',
dashStyle: 'longdash'
}
},
plotOptions: {
series: {
dashStyle: 'longdash'
},
line: {
dataLabels: {
enabled: true
},
enableMouseTracking: true
}
},
series: [{}]
};
$.ajax({
url: "jdatas.php?org="+org+"&ptype="+ptype+"&path="+path+"&mirna="+mirna+"&pid="+id+"&cell="+cell+"&pub="+pubmed,
data: 'show=impressions',
type:'get',
dataType: "json",
success: function(data){
var getSeries = data;
options.series = getSeries;
var chart1 = new Highcharts.Chart(options);
}
});
I want multiple graphs to be loaded on submit.
But its not showing any graph.

How can I convert datetime stamp in jQuery of a Highchart to get the correct format in json?

To start with I must confess I have not so good knowledge of jQuery and Json.
Basically my json encode reads like this ["2013-06-18 09:42:30",6.21],["2013-06-18 09:44:30",6.57],["2013-06-18 10:01:49",6.61],......these are the results of battery voltage in given date and time which keeps updating. There are hundreds of records.
I know this time stamp is not valid while plotting the graph so Yesterday I was trying to tweak the jQuery in jSfiddle to get result and convert it into a chart.
While working in Jsfiddle it said my code is fine but I am getting a blank container area.
Can anyone please guide me on how to convert the datetime stamp in UTC so that a graph can be plotted.
The jQuery which I was tweaking looks like this:
var chart;
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
month: '%e. %b',
year: '%b'
}
},
yAxis: {
title: {
text: 'Battery Voltage'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.dateFormat('%a %d %b %H:%M:%S', this.x) +' : '+ this.y +" V";
}
},
series: [{
name: 'Battery Volatge',
data: []
}]
});
function requestData() {
$.ajax({
url: 'data.php',
datatype: "json",
success: function(data) {
alert(data);
chart.series[0].setData(data);
},
cache: false
});
}
and my PHP looks like this:
<?php
header("Content-type: text/json");
$dbc = mysql_connect('xxxxx','xxxxx','xxxxx') or die(mysql_error());
mysql_select_db('xxxxx',$dbc) or die(mysql_error());
$result = mysql_query("SELECT COUNT(*) AS count FROM Station_State");
$row = mysql_fetch_array($result,MYSQL_ASSOC);
$SQL = "SELECT ss_Stamp,ss_BatteryStatus FROM Station_State WHERE Station_State_Index > 371298 AND ss_Station_idx = 34 ORDER BY ss_Stamp";
$result = mysql_query( $SQL ) or die("Couldn?t execute query.".mysql_error());
$i=0;
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$row[ss_BatteryStatus] = (float) $row[ss_BatteryStatus];
$rows[$i]=array($row[ss_Stamp],$row[ss_BatteryStatus]);
$i++;
}
echo json_encode($rows);
?>
It is probably a basic question but I am still learning so any advice will be appreciated. Do let me know if you need any more information or anything I mentioned sounds vague.
Thanks
You can simple preprocess your data. Before setting data loop through all points, and convert that string to timestamp, for example:
for (var i = 0; i < data.length; i++ ){
data[i][0] = new Date(data[i][0]).getTime();
}
Posting Code which works perfectly. The only problem is the a window pops up with encoded data.
jQuery code:
$(function () {
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart;
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
borderwidth: 0,
events: {
load: requestData
}},
title: {
text: 'Battery Graph'
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
month: '%e. %b',
year: '%b'
}
},
yAxis: {
title: {
text: 'Battery Performance Voltage'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.dateFormat('%a %d %b %H:%M:%S', this.x) +' : '+ this.y +" V";
}
},
series: [{
showInLegend: false,
name: 'Time vs Volatge',
data: []
}]
});
function requestData() {
$.ajax({
url: 'bdata.php',
datatype: "json",
success: function(data) {
alert(data);
for (var i = 0; i < data.length; i++ ){
data[i][0] = new Date(data[i][0]).getTime();
}
chart.series[0].setData(data);
},
cache: false
});
};
});
});
My PHP code looks like this:
<?php
header("Content-type: text/json");
$dbc = mysql_connect('xxxx','xxxx','xxxx') or die(mysql_error());
mysql_select_db('xxxx',$dbc) or die(mysql_error());
$result = mysql_query("SELECT COUNT(*) AS count FROM xxxx");
$row = mysql_fetch_array($result,MYSQL_ASSOC);
$SQL = "SELECT ss_Stamp,ss_BatteryStatus FROM Station_State WHERE Station_State_Index > 377708 AND ss_Station_idx = 34 ORDER BY ss_Stamp";
$result = mysql_query( $SQL ) or die("Couldn?t execute query.".mysql_error());
$i=0;
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$row[ss_BatteryStatus] = (float) $row[ss_BatteryStatus];
$rows[$i]=array($row[ss_Stamp],$row[ss_BatteryStatus]);
$i++;
}
echo json_encode($rows);
?>
Thank you Pawel. You have been great help.

Highcharts Pie Chart from Ajax

I have a page that uses highcharts pie chart, and I am trying to update the chart with a date selector drop down. I have a similar implementation for a bar chart and its working great. Please note (this is coming from a PHP class, hence the concatenation and what not).
<script type='text/javascript'>
function drawPie(data)
{
var chart;
alert('called');
var options = {
chart: {
renderTo: 'PieChart',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
height: 350
},
title: {
text: 'Product Popularity'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {enabled: false},
showInLegend: true
}
},
series: [{
type: 'pie',
name: 'Product Popularity',
data: data
}]
}
chart = new Highcharts.Chart(options);
$('#ProductPieMod div.mod_content').css('height', $('#PieChart').css('height'));
}
$(document).ready(function(){
drawPie(" . $this->get_data($this->date) . ");
$('#ProductPieMod_date').on('change', function(){
var val = parseInt($(this).val());
switch(val)
{
case 0:
var date = Date.today();
break;
case 1:
var date = Date.parse('last week');
break;
case 2:
var date = Date.today().moveToFirstDayOfMonth();
break;
case 3:
var date = Date.parse('January').moveToFirstDayOfMonth();
break;
default:
var date = Date.today();
}
var info;
$.ajax({
type: 'POST',
url: '". matry::base_to('utilities/dhs/manager_dash') . "',
async: false,
dataType: 'json',
data: {date: date.toString('M/dd/yyyy'), module: 'ProductPieMod'},
success: function(data)
{
drawPie(data);
}
});
});
});
</script>
My ajax returns the following string:
[['FASTCLIX LANCING DEVICE', 62.5],['FREESTYLE LANCING DEVICE', 25],['ONETOUCH DELICA LANCING DEVICE', 12.5]]
In addition, this chart is initially built, using the exact same method, just fine. Its just when I use the dropdown (run the onChange event) that it breaks.
Update
I have created a fiddle for this as well: http://jsfiddle.net/SHReZ/1/
Firts, you need to place chart var to document.ready handler scope, next, you need to destroy chart before draw.
$(document).ready(function () {
var chart;
function drawPie(data) {
console.log('called');
var options = {
chart: {
renderTo: 'PieChart',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
height: 350
},
title: {
text: 'Product Popularity'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
type: 'pie',
name: 'Product Popularity',
data: data
}]
};
if (chart !== undefined) chart.destroy();
chart = new Highcharts.Chart(options);
$('#ProductPieMod div.mod_content').css('height', $('#PieChart').css('height'));
}
drawPie([
['ONETOUCH DELICA LANCING DEVICE', 27.78],
['FREESTYLE LANCING DEVICE', 20.83],
['Nova Max Ketone Test Strips Health and', 11.11],
['ONETOUCH ULTRASOFT LANCING DEVICE 2PK', 11.11]
]);
//get data from https://gist.github.com/zba/4712055 , delay 4
$.post('/gh/gist/response.html/4712055', {
delay: 4
}, function (data) {
drawPie(data);
}, 'json');
});
fiddle
also here is demo which not destroy chart, but it change colors to much

Highcharts won't show line through my dots

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.

Categories