creating highcharts with form submit event - php

In my dashboard i have 2 charts created using highcharts . one chart is displayed automatically on load another chart want to change according to the values selected in the drop down box.
I am using php to get the database values according to the drop down box selection. and passing it t0 java script to generate the chart.
my problem is it doesn't showing the second chart .
here is my code:
var chart1;
//$(document).ready(function() {
$("#chartvalue").submit(function() {
var su=<?php echo json_encode($_SESSION['successcalls']) ?>;
var fail=<?php echo json_encode($_SESSION['failurecalls']) ?>;
var da=<?php echo json_encode($_SESSION['datename']) ?>;
alert(su);
chart1 = new Highcharts.Chart({
chart: {
renderTo: 'chartmon_div',
defaultSeriesType: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Call Details',
x: -20 //center
},
subtitle: {
x: -20
},
xAxis: {
categories: da
},
yAxis: {
title: {
text: 'Total calls'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y ;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: [{
name: 'Success',
data: su
}, {
name: 'Failure',
data: fail
}]
});
});
//});
</script>
i have the php variales code in form submit

encrypt your javascript of highchart with PHP condition
<?php if(isset($_POST['variable'])) {
foreach ($productname as $prdkey => $prdval){
foreach ($typecount as $typekey => $typeval)
{
switch ($typeval) {
case 0:
if($producttotal[$prdval][0] != '')
{
$pricecustomstr .= round($producttotal[$prdval][0]).', ';
//$pricecustomtotal = $pricecustomtotal + $producttotal[$prdval][0];
}
else
{
$pricecustomstr .= '0, ';
}
break;
case 1:
if($producttotal[$prdval][1] != '')
{
$priceuploadstr .= round($producttotal[$prdval][1]).', ';
//$priceuploadtotal = $priceuploadtotal + $producttotal[$prdval][1];
}
else
{
$priceuploadstr .= '0, ';
}
break;
case 2:
if($producttotal[$prdval][2] != '')
{
$pricepredefinedstr .= round($producttotal[$prdval][2]).', ';
//$pricepredefinedtotal = $pricepredefinedtotal + $producttotal[$prdval][2];
}
else
{
$pricepredefinedstr .= '0, ';
}
break;
default:
if($producttotal[$prdval][0] != '')
{
$pricecustomstr .= round($producttotal[$prdval][0]).', ';
}
else
{
$pricecustomstr .= '0, ';
}
break;
}
}
}
$productstring;
$pricecustomstr = rtrim(trim($pricecustomstr),', ');
?>
<script type="text/javascript">
// highchart js code
plotOptions: {
series: {
stacking: 'normal'
}
},
series: [{
name: 'Custom Design',
data: [<?php echo $pricecustomstr; ?>]
}, {
name: 'Upload Design',
data: [<?php echo $priceuploadstr; ?>]
});
</script>
<?php } ?>
Thanks

Related

When i scroll Gnatt highcharts some of the data is not shown in some columns

Highchart scroll problem
When I scroll using the in built scroll bar of highcharts, some of the data is not being shown in the highcharts table, but when I scroll again, the data is shown and some other data is omitted out.
The code that I have used is given below for reference
code:-
<?php
$colorArray = ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4'];
$string ='[';
for($i=1;$i<=15;$i++){
$yearString = rand(2016,2018);
$monthString = rand(1,12);
$dateString = rand(1,28);
$endYearString = rand(2019,2021);
$string .= "{ start: Date.UTC($yearString, $monthString, $dateString),end: Date.UTC($endYearString, $monthString, $dateString),name: 'Initiative ".$i."',color: '".$colorArray[rand(0,8)]."', label:'Initiative ".$i."' },";
}
$string .= "{ start: Date.UTC(2020, 1, 1),end: Date.UTC(2021, 1, 12),name: 'Qus',color: '".$colorArray[rand(0,8)]."', label:'Qus' },";
$string .= "{ start: Date.UTC(2021, 1, 12),end: Date.UTC(2021, 1, 22),name: 'Qus',color: '".$colorArray[rand(0,8)]."', label:'Qus' },";
$string .= "{ start: Date.UTC(2021, 1, 23),end: Date.UTC(2021, 5, 31),name: 'Qus',color: '".$colorArray[rand(0,8)]."', label:'Qus' },";
for($i=1;$i<=30;$i++){
$yearString = rand(2016,2018);
$rnd = rand(1,5);
for($j=1;$j<$rnd;$j++){
$monthString = rand(1,12);
$dateString = rand(1,28);
$endMonthString = rand(1,12);
$endDateString = rand(1,28);
$endYearString = rand(2016,2021);
$string .= "{ start: Date.UTC($yearString, $monthString, $dateString),end: Date.UTC($endYearString, $endMonthString, $endDateString),name: 'Qus ".$i." - ".$j."',color: '".$colorArray[rand(0,8)]."', label:'Qus ".$i." - ".$j."' },";
}
}
$string .= "]";
// echo $string;die;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://code.highcharts.com/gantt/highcharts-gantt.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<style>
#container {
max-width: 1200px;
margin: 1em auto;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
Highcharts.setOptions({
colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4']
});
Highcharts.ganttChart('container', {
chart: {
spacingLeft: 1,
style: {
fontFamily: ' Roboto, sans-serif;',
// fontWeigth: 'bolder'
}
},
title: {
text: 'Gantt Chart with Navigation'
},
yAxis: {
uniqueNames: true,
min: 0,
max: 7,
scrollbar:{
enabled : true
}
},
xAxis: {
currentDateIndicator: true,
type: 'category',
title: {
text: null
},
min: 0,
// max: 8,
scrollbar: {
enabled: true
},
tickLength: 0
},
tooltip: {
xDateFormat: '%a %b %d, %H:%M'
},
plotOptions:{
series: {
pointWidth: 13,
dataLabels: {
enabled: true,
format: '{point.label}',
style: {
cursor: 'default',
pointerEvents: 'none'
}
},
}
},
navigator: {
enabled: true,
series: {
type: 'gantt',
pointPlacement: 0.5,
pointPadding: 0.25
},
yAxis: {
min: 0,
max: 3,
reversed: true,
categories: []
}
},
scrollbar: {
enabled: true
},
rangeSelector: {
enabled: true,
selected: 5
},
series: [{
name: 'Project 1',
events:{
click: function(event){
console.log(event)
console.log(this)
alert("Clicked");
}
},
dataLabels: {
enabled: true,
style: {
textOutline: 0
}
},
data: <?php echo $string; ?>
}]
});
const callback = function(){
let text = document.querySelectorAll('.highcharts-data-label-color-undefined')
let box = document.querySelectorAll('.highcharts-partfill-original')
text.forEach((el,index)=>{
let child = el.children[0];
let boxWidth = box[index].getBoundingClientRect().width;
let textWidth = child.getBoundingClientRect().width;
// console.log(textWidth,boxWidth)
if (textWidth > boxWidth){
child.style.opacity = "0";
}else{
// child.textContent = z;
child.style.fill = "white";
child.style.opacity = "1";
}
})
};
callback();
window.addEventListener('resize', callback);
</script>
</body>
</html>
scrollbar:{
enabled : true
},
events: {
setExtremes: function(e){
let main = document.querySelector('.highcharts-plot-background').getBoundingClientRect();
const call = function(){
let bound = main.y + main.height;
let lines = document.querySelectorAll('.highcharts-tick')
let texts = document.querySelectorAll('.highcharts-treegrid-node-level-1');
texts.forEach(el=>{
let textlines = el.getBoundingClientRect();
if(textlines.y > main.y && textlines.y < bound-20){
el.style.visibility = "visible"
}else{
el.style.visibility = "hidden"
}
})
lines.forEach(el=>{
let pathlines = el.getBoundingClientRect();
let parent = el.parentNode
if(parent.classList.contains('highcharts-yaxis')){
if(pathlines.y > main.y && pathlines.y <bound){
el.style.visibility = "visible"
el.visibility = "visible"
}else{
el.style.visibility = "hidden"
el.visibility = "hidden"
}
}
})
}
setTimeout(function(){ call();},500)
}
}
},

passing data to https using JSONP for highcharts which get date range from user

I had posted : passsing data to https by JSON using JSONP ,and tried to change the highchart by call back to JSONP but still I don't get any result. Could any one tell me what is the problem (perhaps I think the way, which I callback is wrong.)?
data.php:
<?php header("content-type: application/json");
$servername = "xxxxxx";
$username = "xxxxxx";
$password = "xxxxxx";
$dbname = "xxxxxx";
$con = mysql_connect($servername,$username,$password,$dbname);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xxxxxxxxxx", $con);
if (isset($_GET["dateparam"])) {
$sql = mysql_query("SELECT timestamp_value, User_Logins FROM foot_traffic WHERE timestamp_value LIKE '".$_GET["dateparam"]."%'");
} else {
$sql = mysql_query("SELECT timestamp_value, User_Logins FROM foot_traffic WHERE timestamp_value LIKE '2013-02-01%'");
}
$result['name'] = 'User_Logins over Time Period';
while($r = mysql_fetch_array($sql)) {
$datetime = $r['timestamp_value'];
$result['category'][] = $datetime;
$result['data'][] = $r['User_Logins'];
}
echo $_GET['callback']. '('. json_encode($result) . ')';
print json_encode($result, JSON_NUMERIC_CHECK);
mysql_close($con);
?>
file.php:
<html>
<head>
<script type="text/javascript">
var hey;
$(document).ready(function() {
hey = {
chart: {
renderTo: 'container1',
type: 'area',
borderColor: "#3366ff",
borderWidth:5,
zoomType : 'x'
},
title: {
text: 'All User_Logins of your All Organizations '
},
subtitle: {
text: ' '
},
credits:{
enabled:false
},
xAxis: {
categories: [],
labels: {
align: 'center',
x: -3,
y: 20,
formatter: function(){
return Highcharts.dateFormat('%l%p',Date.parse(this.value +' UTC'));
}
}
},
yAxis: {
title: {
text: ''
}
},
tooltip: {
backgroundColor: '#FCFFC5',
borderColor: 'black',
borderRadius: 10,
borderWidth: 3
},
// Enable for both axes
tooltip: {
borderWidth: 0,
backgroundColor: "rgba(255,255,255,0)",
borderRadius: 0,
shadow: false,
useHTML: true,
percentageDecimals: 2,
backgroundColor: "rgba(255,255,255,1)",
formatter: function () {
return '<div class="tooltip">' + this.point.name + '<br />' + '<b>' +
Highcharts.numberFormat(this.y).replace(",", " ") + ' Kč [' +
Highcharts.numberFormat(this.percentage, 2) + '%]</b></div>';
}
},
plotOptions: {
line: {
dataLabels: {
enabled: true
},
enableMouseTracking: false
}
},
series: [{
type: 'area',
name: '',
data: []
}]
}
$.getJSON("data.php?callback=?", function(json){
hey.xAxis.categories = json['category'];
hey.series[0].name = json['name'];
hey.series[0].data = json['data'];
chart = new Highcharts.Chart(hey);
});
});
$(function() {
$( "#datepicker" ).datepicker({
dateFormat: "yy-mm-dd",
showOn: "button",
buttonImage: "calendar.gif",
buttonImageOnly: true,
onSelect: function(dateText, inst) {
$.getJSON("data.php?dateparam?callback=?"+dateText, function(json){
hey.xAxis.categories = json['category'];
hey.series[0].name = json['name'];
hey.series[0].data = json['data'];
chart = new Highcharts.Chart(hey);
});
}
});
});
</script>
</head>
<body>
<!--date picker-->
<input type="text" id="datepicker" />
<!-- highchart container-->
<div id="container1" class="analysis" style=" margin: 0 auto">
</div>
</body>
</html>

Highcharts multiple series json from php

Hi guys i need help with Highcharts library, i have this array coming from php,
[{"name":"25% en cambio de aceite 76 lubricants","data":[["2015-09-07",1],["2015-09-23",2],["2015-09-24",3],["2015-09-30",3]]},{"name":"10% Descuento en filtro de aceite","data":[["2015-09-07",1],["2015-09-23",2],["2015-09-24",3],["2015-09-30",3],["2015-10-03",3],["2015-10-05",1],["2015-10-09",1],["2015-10-10",1]]}]
I need to show this as line chart dynamically, but have been unable to do it, i believe the error comes from the quotes in dates, needs to be in format [Date.UTC(2015, 2, 6), 3]
This is my php function that returns the json data
public function actionTransactionsRedeemed() {
// Transacciones Totales redimidas por merchant
$sql = "SELECT DISTINCT `transaction`.idPromotion, promotion.`name` FROM `transaction` INNER JOIN promotion ON `transaction`.idPromotion = promotion.idPromotion WHERE `transaction`.idMerchant = 2 AND `transaction`.idPromotion IS NOT NULL";
$idPromotion = Yii::app()->db->createCommand($sql)->queryAll();
$idPromotions = array();
$tempArray = array();
$result = array();
$i = 1;
$rs = array();
foreach($idPromotion as $i){
//process each item here
$id = $i["idPromotion"];
$tempArray['name'] = $i["name"];
$sql = "SELECT count(*) AS count, DATE(`transaction`.date) AS `date` FROM `transaction` WHERE `transaction`.idMerchant = 2 AND `transaction`.idPromotion = $id GROUP BY DATE(`transaction`.date)";
$transactionsRedeemed = Yii::app()->db->createCommand($sql)->queryAll();
foreach($transactionsRedeemed as $item2){
$rs[0] = $item2['date'];
$rs[1] = $item2['count'];
$tempArray['data'][] = $rs;
$rs = array();
}
$i++;
array_push($result, $tempArray);
}
//$result = json_encode($result, JSON_NUMERIC_CHECK);
//echo json_decode($result);
print json_encode($result, JSON_NUMERIC_CHECK);
}
And this is the Jquery that builds the chart
$(document).ready(function() {
var options = {
chart: {
type: 'spline',
renderTo: 'chart-merchant-day',
defaultSeriesType: 'spline',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Total de promociones redimidas',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: { // don't display the dummy year
month: '%e. %b',
year: '%b'
},
labels: {
align: 'center',
x: -3,
y: 20,
formatter: function() {
return Highcharts.dateFormat('%l%p', this.value);
}
}
},
yAxis: {
title: {
text: 'Transacciones'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return Highcharts.dateFormat('%l%p', this.x-(24000*3600)) +'-'+ Highcharts.dateFormat('%l%p', this.x) +': <b>'+ this.y + '</b>';
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: [{
name: 'Count'
}],
credits: false
}
// Load data asynchronously using jQuery. On success, add the data
// to the options and initiate the chart.
jQuery.get('?r=/transactions/transactionsRedeemed', null, function(tsv) {
var lines = [];
traffic = [];
var data = $.parseJSON(tsv);
var x = 0;
//console.log(tsv);
$.each(data, function(i, item) {
//alert(item);
//console.log(item);
$.each(item, function(y, item2) {
if(y == "data"){
//console.log(item2);
try {
tsv = item2;
// split the data return into lines and parse them
tsv = tsv.split(/\n/g);
jQuery.each(tsv, function(i, line) {
line = line.split(/\t/);
options.series[x].data.push([Date.parse(line[0]),line[1]]);
/*date = Date.parse(line[0] +' UTC');
traffic.push([
date,
parseInt(line[1].replace(',', ''), 10)
]);*/
});
} catch (e) { }
options.series[x].data = traffic;
} else if(y == "name"){
options.series[x].name = item2;
}
});
x++;
});
chart = new Highcharts.Chart(options);
//console.log(tsv.replace(/\"/g, ""));
//tsv = tsv.replace(/\"/g, "");
});
});
Any help will be greatly appreciated, im so exhausted at this point.
The function is actually simpler,
jQuery.get('?r=/transactions/transactionsRedeemed', null, function(tsv) {
var data = $.parseJSON(tsv);
$.each(data, function (i, item) {
options.series.push({
name: item['name'],
data: []
});
$.each(item['data'], function (j, dataitem) {
var dataitemvalue = null;
try {
dataitemvalue = [Date.parse(dataitem[0]), dataitem[1]];
} catch (e) {}
options.series[i].data.push(dataitemvalue);
});
});
chart = new Highcharts.Chart(options);
});
JSFiddle demo

how to create proper json data format from mysql for highcharts

I have a json data that will retrive the selected data from database based on user checked on checkboxes. but I know my json data is not correct. Tried many way, but still wont works. This is the code:
<?php
foreach ($_GET['iddoc'] as $iddoc) //iddoc is the value of checked checkbox
{
$query="select * from compareresult where iddocument=$iddoc";
$sql_query = mysql_query($query) or die('Error 3 :'.mysql_error());
while ($r = mysql_fetch_assoc($sql_query))
{
$series1['name'][] = $r['subject'];
$series1['data'][] = $r['result'];
}
$jsonTable = json_encode($series1, JSON_NUMERIC_CHECK);
echo $jsonTable;
}
Based from the code below, lets say if I checked 3 checkbox (BAT123, BIO222, HIS TEST),The json output will be like this:
{"name":["BAT123"],"data":[3.03]}
{"name":["BAT123","BIO222"],"data":[3.03,1.05]}
{"name":["BAT123","BIO222","his test"],"data":[3.03,1.05,3.03]}
I know the json above was wrong, So how to make the json data will be display like this:
[
{"name":["BAT123"],"data":[3.03]},
{"name":["BIO222"],"data":[1.05]},
{"name":["his test"],"data":[3.03]}
]
This is my highcharts javascript code:
<script type="text/javascript">
$(function () {
var data = [
<?php echo $jsonTable; ?>
];
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'SamHistogramDiv',
type: 'column',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'SAM Histogram Results',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Percentage'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: data[0]
});
});
});
Thank u very much for your time..
Problem was with the json data format. It should be like
var data = [{name:"BAT123",data:[3.03]},{name:"BIO222",data:[1.05]},{name:"his test",data:[3.03]}];
foreach ($_GET['iddoc'] as $iddoc) //iddoc is the value of checked checkbox
{
$query="select * from compareresult where iddocument=$iddoc";
$sql_query = mysql_query($query) or die('Error 3 :'.mysql_error());
while ($r = mysql_fetch_assoc($sql_query))
{
$series[] = array('name'=>$r['subject'],'data'=>array($r['result']));
}
}
$jsonTable = json_encode($series);
echo $jsonTable;
Pls check if you are getting the json string as mentioned above /* data */
Check this link
http://jsfiddle.net/highcharts/Sq3KL/2/
Try this
foreach ($_GET['iddoc'] as $iddoc) //iddoc is the value of checked checkbox
{
$query="select * from compareresult where iddocument=$iddoc";
$sql_query = mysql_query($query) or die('Error 3 :'.mysql_error());
while ($r = mysql_fetch_assoc($sql_query))
{
$series[] = array('name'=>$r['subject'],'data'=>$r['result']);
}
}
$jsonTable = json_encode($series);
echo $jsonTable;
the out put will be like
[{"name":"BAT123","data":"3.03"},{"name":"BIO222","data":"1.05"},{"name":"HIs test","data":"1.00"}]

highcharts are not displayed in jquery ui tabs with ie8

I'm actually using jquery-ui tabs. I need to put in each tab some charts from HighCharts library. It works fine on firefox, but the problem is on IE8. Indeed, charts are not displayed at all, and it seems to crash when generating charts.
I'm sorry i can't give you an url example.
Here is the code of one chart :
$(document).ready(function() {
var chart1 = new Highcharts.Chart({
chart: {
renderTo: 'container1',
borderColor: '#CCCCCC',
borderWidth: 2,
type: 'line',
height : ".$height.",
width : ".$width.",
zoomType: 'x'
},
title: {
text: 'exemple'
},
subtitle: {
text: 'subtitle'
},
xAxis: {
categories: ['" . implode("', '", $xValues) . "'],
type:'datetime',
maxZoom: 1
},
yAxis: {
title: {
text: 'ordonnees'
}
},
exporting: {
type : 'image/png',
scale: 2
},
plotOptions: {
line: {
dataLabels: {
enabled: true
},
marker:{
enabled: true
}
}
},
series: [";
$d = "";
foreach($data as $leg => $val)
{
$s = implode(', ', $val);
$d .= "{ name: '$leg',
data: [" . $s . "] }, ";
}
$sortie .= $d;
$sortie .= "]
});
});
Can you help me please ?

Categories