Related
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)
}
}
},
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>
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
My highcharts chart is showing like this now:
http://img90.imageshack.us/img90/3892/chart1p.png
But I need it to look like this:
http://img545.imageshack.us/img545/1333/chart2p.png
Currently its not showing empty values by hours.
My code:
index.php
<script type="text/javascript" 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">
var chart;
$(document).ready(function () {
var options = {
chart: {
renderTo: 'chart',
defaultSeriesType: 'spline'
},
title: {
text: 'Earnings Today',
},
subtitle: {
text: ''
},
xAxis: {
type: 'datetime',
tickInterval: 3600 * 1000,
tickWidth: 0,
labels: {
align: 'center',
formatter: function () {
return Highcharts.dateFormat('%l%p', this.value);
}
},
},
yAxis: {
title: {
text: 'Earnings'
},
min: 0,
tickInterval: 2,
},
plotOptions: {
spline: {
marker: {
radius: 4,
lineColor: '#666666',
lineWidth: 1
}
}
},
tooltip: {
valueDecimals: 2,
crosshairs: true,
formatter: function () {
return '$' + this.y;
}
},
series: [{
name: 'Earnings Today, USD'
}
]
}
jQuery.get('data_today.php', null, function (tsv) {
var lines = [];
earnings = [];
try {
tsv = tsv.split(/\n/g);
jQuery.each(tsv, function (i, line) {
line = line.split(/\t/);
date = Date.parse(line[0] + ' UTC');
val = line[1];
earnings.push([date, parseFloat(line[1].replace(',', '.'), 10)]);
});
} catch (e) {}
options.series[0].data = earnings;
chart = new Highcharts.Chart(options);
});
});
</script>
data_today.php
<?php
session_start();
require_once('config.php');
require_once('config_mysql.php');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link)
{
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if (!$db)
{
die("Unable to select database");
}
$result = mysql_query("SELECT earn_date,SUM(amount) as val FROM user_earnings WHERE user_id='$USER_ID' AND DATE(earn_date) = DATE(NOW()) GROUP BY earn_date");
if ($result)
{
while ($row = mysql_fetch_array($result))
{
$d = date("l, F, j, Y G:i:s", strtotime($row["earn_date"]));
echo $d . "\t" . $row['val'] . "\n";
}
}
else
{
die(mysql_error());
}
mysql_close($link);
?>
So, (if its not enough clear yet) I need this code to show whole day and show also empty values by hour.
I have almost zero experience of highcharts and javascript, so I need some help with this :)
Also looking for alternative way for running MySql query inside index.php so I dont need data_today.php
Thanks
Set the xAxis as below
xAxis: {
ordinal: false
}
For empty spaces you should have null values. Then set connectNulls: false.
Example
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