I would appreciate some guidance on the following issue. I am by no means an expert in php. The code below takes almost 10 seconds to execute! Is there anything I am doing that is wrong or bad practice?
$data = [];
$today = date("Y/m/d");
$ThisYear = Date('Y'); //get current Year
$ThisMonth = Date('m'); //get current month
$Tday = '01'; //first day of month
$Tmonth = '09'; //September
if (8 < $ThisMonth && $ThisMonth < 13) {
$AcYear = $ThisYear; }
else {
$AcYear = $ThisYear - 1; // sets start of academic year to be last year
}
$AcFullYear = $AcYear.'/'.$Tmonth.'/'.$Tday;
//find rank in all school
$students_rank = [];
$school_id = Student::model()->findByAttributes(['user_master_id' => Yii::app()->user->id])->school_master_id;
$criteria1 = new CDbCriteria;
$criteria1->with = array('user');
$criteria1->condition = "t.school_master_id=:school_master AND user.status ='1'";
$criteria1->params = array(':school_master' => $school_id);
$school_students_details = Student::model()->findAll($criteria1);
foreach ($school_students_details as $key => $value) {
$student_name = StudentDetails::model()->findByAttributes(['user_master_id' => $value->user_master_id]); //student details with year group
$criteria2 = new CDbCriteria;
$criteria2->with = array('homeworkMaster');
$criteria2->condition = "t.student_id=:student_id AND homeworkMaster.question_type_id<>:question_type_id";
$criteria2->params = array(':student_id' => $value->user_master_id, ':question_type_id' => 6);
$HW_assignment_track = HomeworkAssignmentTrack::model()->findAll($criteria2);
$total_HW = count((array)$HW_assignment_track);
$student_score = 0;
$student_rank = 0;
$student_total_score = 0;
$total_HW_marks = 0;
$under_deadline_HW = 0;
$criteria3 = new CDbCriteria();
$criteria3->condition = "student_id =:student_id AND status=:status AND created_at >= '$AcFullYear' AND created_at <= '$today'";
$criteria3->params = [':student_id' => $value->user_master_id, ':status' => 2];
$student_completed_HW = HomeworkStudentAnswere::model()->findAll($criteria3);
$i = 1;
foreach ($student_completed_HW as $s_c_h_K => $s_c_h_V) {
if ($s_c_h_V->homework->homework_type == 2) {
$total_HW -= 1;
} elseif ($s_c_h_V->homework->homework_type == 1) {
$HW_questions = HomeworkQuestion::model()->findAllByAttributes(['homework_master_id' => $s_c_h_V->homework_id, 'status' => 1]);
foreach ($HW_questions as $qKey => $qVal) {
if ($qVal->question_type_id ==3) {
$total_HW_marks += 2;
} else {
$total_HW_marks += $qVal->marks;
}
}
$assignment = HomeworkAssignmentTrack::model()->findByAttributes(['id' => $s_c_h_V->assignment_track_id]);
$homeworks_within_validate = Assignment::model()->findByPk($assignment->assignment_id);
if ($homeworks_within_validate->valid_date === '0' && $homeworks_within_validate->deadline >= date('Y-m-d')) {
$total_HW -= 1;
}
if ($homeworks_within_validate->valid_date === '1' || (($homeworks_within_validate->valid_date === '0') && ($homeworks_within_validate->deadline >= date('Y-m-d', strtotime($s_c_h_V->created_at))) && ($homeworks_within_validate->deadline < date('Y-m-d')))) {
if ($s_c_h_V->review_status === '2') {
$student_total_score += $s_c_h_V->score;
}
}
$homework_submit = HomeworkCompleteNotification::model()->findByAttributes(['homework_id' => $s_c_h_V->homework_id, 'assignment_track_id' => $s_c_h_V->assignment_track_id, 'student_id' => $value->user_master_id]);
if (($homeworks_within_validate->valid_date === '0') && ($homeworks_within_validate->deadline >= date('Y-m-d', strtotime($homework_submit->created_at))) && ($s_c_h_V->review_status === '2')) {
$under_deadline_HW += 10;
}
if ($total_HW_marks !=0) {
$student_score += round(($student_total_score / $total_HW_marks) * 100);
} else {
$student_score = 0;
}
}
$i += 1;
}
//add revision scores to rank score
$criteria4 = new CDbCriteria();
$criteria4->condition = "user_id =:user_id AND date_created >= '$AcFullYear' AND date_created <= '$today'";
$criteria4->params = [':user_id' => $value->user_master_id];
$revision_score = RevisionScores::model()->findAll($criteria4);
$sum = 0;
foreach($revision_score as $item) {
$sum += $item['score'];
} //end of adding revision scores
$students_rank[$key]['student_id'] = $value->user_master_id;
$students_rank[$key]['year_group'] = $student_name->year_group_id; //added year group to model array
if ($student_score > 0) {
$student_rank += round($student_score / $total_HW, 0) + $under_deadline_HW;
$students_rank[$key]['rank'] = $student_rank + $sum;
} else {
$students_rank[$key]['rank'] = $sum;
}
}
$model = $this->multid_sort($students_rank, 'rank');
$rank_score = round(array_column($model, 'rank', 'student_id')[Yii::app()->user->id],0);
$year_rank =[];
$current_st = StudentDetails::model()->findByAttributes(['user_master_id' => Yii::app()->user->id]);
$current_st_year = $current_st->year_group_id;
$rank_list = [];
foreach ($model as $key => $value) {
$rank_list[] = $value['student_id'];
if ($value['year_group'] == $current_st_year) {
$year_rank[] = $value['student_id'];
}
}
$user = Yii::app()->user->id;
$sch_position = array_search($user,$rank_list);
$yr_position = array_search($user,$year_rank);
$final_rank = $sch_position + 1;
$yr_rank = $yr_position + 1;
$sch_rank = $final_rank;
$ends = array('th','st','nd','rd','th','th','th','th','th','th');
if (($sch_rank %100) >= 11 && ($sch_rank%100) <= 13) {
$sc_abbreviation = 'th';
$yr_abbreviation = 'th';
} else {
$sc_abbreviation = $ends[$sch_rank % 10];
$yr_abbreviation = $ends[$yr_rank % 10];
}
$models = UserMaster::model()->findByPk(Yii::app()->user->id);
$year_name = $models->studentDetails->yearGroup->name;
$data['type'] = 'success';
$data['score'] = '<div>Ranking Score: '.$rank_score.'</div>';
$data['yr_rank'] = '<div><i class="fa fa-trophy rank-i"></i><span class="rank-number">' .$yr_rank. '</span><sup class="script-top" id="year_rank_abb">' .$yr_abbreviation. '</sup></div><div id="year_name">In ' .$year_name. '</div>';
$data['school_rank'] = '<div><i class="fa fa-trophy rank-i"></i><span class="rank-number">' .$sch_rank. '</span><sup class="script-top" id="year_rank_abb">' .$sc_abbreviation. '</sup></div><div id="year_name">In School</div>';
$data['rank_revise'] ='<div>'.$rank_score.'</div>';
$data['yr_rank_revise'] = '<span>'.$yr_rank.'</span><sup class="superscript" style="left:0">'.$yr_abbreviation.'</sup>';
$data['sch_rank_revise'] = '<span>'.$sch_rank.'</span><sup class="superscript" style="left:0">'.$sc_abbreviation.'</sup>';
$_SESSION['rank'] = $rank_score;
$_SESSION['accuracy'] = $rank_score;
echo json_encode($data);
exit;
The above is used in an Yii application. It runs perfectly fine on localhost, but on live site, takes over 10 seconds to execute.
Your help and guidance is appreciated.
Thank
I'm using highcharts plugin to print stats in a codeigniter site.
Now I get the data from my database I manage it but when I print it inside highcharts nothing is printed.
This is my php code:
$arr_point = array();
$check_price = array();
for($i = 1; $i <= 12; $i++){
$sum = 0;
$this->load->model('backend/Notification_model');
$this->db->select('*,');
$this->db->from('booking');
$query = $this->db->get();
foreach ($query->result() as $row){
$sum+=(float)$row->total_with_markup;
}
$arr_point[] = str_replace(',', '.', $sum);
}
$result = array();
array_push($result,$arr_point);
return(json_encode($result));
and this is my highchart configuration:
$('#container').highcharts({
chart: {
type: 'column'
},
title: {
text: $('#riepilogo option:selected').text()
},
subtitle: {
text: ''
},
xAxis: {
categories: [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
]
},
yAxis: {
min: 0,
title: {
text: 'Euro'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.2f} euro</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [ {
name: $('#riepilogo options:selected').text(),
data: "<?php echo json_decode($data_chart); ?>"
}]
});
});
if I print json_decode($data_chart) I get this:
Array
if I print ($data_chart I get this:
[["0","297.23","74.41","65.57","2167.32","7649.77","2058.05","146.95","92.55","0","1754.72","0"]]
I have try to not use json_encode, to use json_decode, nothing. Can someone help me? Thanks
The problem is that you create an array in your script:
$arr_point = array();
Try returning just the array and delete:
$result = array();
array_push($result,$arr_point);
and return $array_point;
Or try:
$arr_point = "";
$check_price = array();
for ($i = 1; $i <= 12; $i++) {
$sum = 0;
$this->load->model('backend/Notification_model');
$this->db->select('*,');
$this->db->from('booking');
$query = $this->db->get();
foreach ($query->result() as $row) {
$sum+=(float) $row->total_with_markup;
}
if($arr_point == ""){
$arr_point .= "[";
}
if($arr_point != ""){
$arr_poin .= ",";
}
$arr_point .= str_replace(',', '.', $sum);
}
$arr_point .= "]";
return $arr_point;
Your code contains many injections, so I advice to print json inside your php file like:
echo json_encode($arr, JSON_NUMERIC_CHECK);
Then in javascript call $.getJSON() function and use it in highcahrts, skipping decoding / missing types of data.
position absolute doesn't work in mozilla. For jquery calender I used position:absolute for a div it seems to work all except mozilla in windows. When I remove the position:absolute it will work in windows firefox but only showing alternate months in all other browsers
jquery is
var CalendarEightysix = new Class({
Implements: Options,
options: {
'slideDuration': 500,
'fadeDuration': 200,
'toggleDuration': 200,
'fadeTransition': Fx.Transitions.linear,
'slideTransition': Fx.Transitions.Quart.easeOut,
'prefill': true,
'defaultDate': null,
'linkWithInput': true,
'theme': 'default',
'defaultView': 'month',
'startMonday': false,
'alwaysShow': false,
'injectInsideTarget': false,
'format': '%n/%d/%Y',
'alignX': 'right',
'alignY': 'ceiling',
'offsetX': 0,
'offsetY': 0,
'draggable': false,
'pickable': true,
'toggler': null,
'pickFunction': $empty,
'disallowUserInput': false,
'minDate': null,
'maxDate': null,
'excludedWeekdays': null,
'excludedDates': null,
'createHiddenInput': false,
'hiddenInputName': 'date',
'hiddenInputFormat': '%t'
},
initialize: function(target, options) {
this.setOptions(options);
this.target = $(target);
this.transitioning = false;
//Extend Date with unix timestamp parser
Date.defineParser({
re: /^[0-9]{10}$/,
handler: function(bits) { return new Date.parse('Jan 01 1970').set('seconds', bits[0]); }
});
//Selected date
if($defined(this.options.defaultDate)) this.selectedDate = new Date().parse(this.options.defaultDate).clearTime();
else if(this.options.linkWithInput && $chk(this.target.get('value'))) this.selectedDate = new Date().parse(this.target.get('value')).clearTime();
if(!$defined(this.selectedDate) || !this.selectedDate.isValid()) this.selectedDate = new Date();
this.viewDate = this.selectedDate.clone().set('date', 1).clearTime();
//Base
var innerHtml = '<div class="wrapper"><div class="header"><div class="arrow-left"></div><div class="arrow-right"></div><div class="label clickable"></div></div>'+
'<div class="body"><div class="inner"><div class="container a"></div><div class="container b"></div></div></div><div class="footer"></div></div>';
this.element = new Element('div', { 'class': 'calendar-eightysix', 'html': innerHtml, 'style': 'display: '+ (this.options.alwaysShow ? 'block' : 'none') }).addClass(this.options.theme);
if(this.options.injectInsideTarget) this.element.injectBottom(this.target);
else {
this.element.injectBottom($(document.body));
this.position();
window.addEvent('resize', this.position.bind(this));
}
this.currentContainer = this.element.getElement('.container.a').setStyle('z-index', 999);
this.tempContainer = this.element.getElement('.container.b').setStyle('z-index', 998);
//Header
this.header = this.element.getElement('.header');
this.label = this.header.getElement('.label');
this.arrowLeft = this.header.getElement('.arrow-left');
this.arrowRight = this.header.getElement('.arrow-right');
this.label.addEvent('click', this.levelUp.bind(this));
this.arrowLeft.addEvent('click', this.slideLeft.bind(this));
this.arrowRight.addEvent('click', this.slideRight.bind(this));
//Date range
if($defined(this.options.minDate)) {
this.options.minDate = Date.parse(this.options.minDate).clearTime();
if(!this.options.minDate.isValid()) this.options.minDate = null;
}
if($defined(this.options.maxDate)) {
this.options.maxDate = Date.parse(this.options.maxDate).clearTime();
if(!this.options.maxDate.isValid()) this.options.maxDate = null;
}
//Excluded dates
if($defined(this.options.excludedDates)) {
var excludedDates = [];
this.options.excludedDates.each(function(date) {
excludedDates.include(this.format(new Date().parse(date).clearTime(), '%t'));
}.bind(this));
this.options.excludedDates = excludedDates;
}
//Dragger
if(this.options.draggable && !this.options.injectInsideTarget) {
this.header.addClass('dragger');
new Drag(this.element, { 'handle': this.header });
}
//Hidden input
if(this.options.createHiddenInput) {
this.hiddenInput = new Element('input', { 'type': 'hidden', 'name': this.options.hiddenInputName }).injectAfter(this.target);
}
//Prefill date
if(this.options.prefill) this.pick();
//Link with input
if(!this.options.disallowUserInput && this.options.linkWithInput && this.target.get('tag') == 'input') {
this.target.addEvent('keyup', function() {
this.setDate(this.target.get('value'), false);
}.bind(this));
}
//Disallow input
if(this.options.disallowUserInput && this.target.get('tag') == 'input')
this.target.addEvents({ 'keydown': ($lambda(false)), 'contextmenu': ($lambda(false)) });
//Toggler
if($defined(this.options.toggler)) this.options.toggler = $(this.options.toggler);
//Show / hide events
($defined(this.options.toggler) ? this.options.toggler : this.target).addEvents({
'focus': this.show.bind(this), 'click': this.show.bind(this)
});
if(!this.options.alwaysShow) document.addEvent('mousedown', this.outsideClick.bind(this));
MooTools.lang.addEvent('langChange', function() { this.render(); this.pick(); }.bind(this));
//View
this.view = this.options.defaultView;
this.render();
},
render: function() {
this.currentContainer.empty();
switch(this.view) {
case 'decade': this.renderDecade(); break;
case 'year': this.renderYear(); break;
default: this.renderMonth();
}
},
renderMonth: function() {
this.view = 'month';
this.currentContainer.empty().addClass('month');
if(this.options.pickable) this.currentContainer.addClass('pickable');
var lang = MooTools.lang.get('Date'), weekdaysCount = this.viewDate.format('%w') - (this.options.startMonday ? 1 : 0);
if(weekdaysCount == -1) weekdaysCount = 6;
var today = new Date();
//Label
this.label.set('html', lang.months[this.viewDate.get('month')] +' '+ this.viewDate.format('%Y'));
//Day label row
var row = new Element('div', { 'class': 'row' }).injectBottom(this.currentContainer);
for(var i = (this.options.startMonday ? 1 : 0); i < (this.options.startMonday ? 8 : 7); i++) {
var day = new Element('div', { 'html': lang.days[this.options.startMonday && i == 7 ? 0 : i] }).injectBottom(row);
day.set('html', day.get('html').substr(0, 2));
}
//Add days for the beginning non-month days
row = new Element('div', { 'class': 'row' }).injectBottom(this.currentContainer);
y = this.viewDate.clone().decrement('month').getLastDayOfMonth();
for(var i = 0; i < weekdaysCount; i++) {
this.injectDay(row, this.viewDate.clone().decrement('month').set('date', y - (weekdaysCount - i) + 1), true);
}
//Add month days
for(var i = 1; i <= this.viewDate.getLastDayOfMonth(); i++) {
this.injectDay(row, this.viewDate.clone().set('date', i));
if(row.getChildren().length == 7) {
row = new Element('div', { 'class': 'row' }).injectBottom(this.currentContainer);
}
}
//Add outside days
var y = 8 - row.getChildren().length, startDate = this.viewDate.clone().increment('month').set('date', 1);
for(var i = 1; i < y; i++) {
this.injectDay(row, startDate.clone().set('date', i), true);
}
//Always have six rows
for(var y = this.currentContainer.getElements('.row').length; y < 7; y++) {
row = new Element('div', { 'class': 'row' }).injectBottom(this.currentContainer);
for(var z = 0; z < 7; z++) {
this.injectDay(row, startDate.clone().set('date', i), true);
i++;
}
}
this.renderAfter();
},
//Used by renderMonth
injectDay: function(row, date, outside) {
today = new Date();
var day = new Element('div', { 'html': date.get('date') }).injectBottom(row);
day.date = date;
if(outside) day.addClass('outside');
if(($defined(this.options.minDate) && this.format(this.options.minDate, '%t') > this.format(date, '%t')) ||
($defined(this.options.maxDate) && this.format(this.options.maxDate, '%t') < this.format(date, '%t')) ||
($defined(this.options.excludedWeekdays) && this.options.excludedWeekdays.contains(date.format('%w').toInt())) ||
($defined(this.options.excludedDates) && this.options.excludedDates.contains(this.format(date, '%t'))))
day.addClass('non-selectable');
else if(this.options.pickable) day.addEvent('click', this.pick.bind(this));
if(date.format('%x') == today.format('%x')) day.addClass('today');
if(date.format('%x') == this.selectedDate.format('%x')) day.addClass('selected');
},
renderYear: function() {
this.view = 'year';
this.currentContainer.addClass('year-decade');
var today = new Date(), lang = MooTools.lang.get('Date').months;
//Label
this.label.set('html', this.viewDate.format('%Y'));
var row = new Element('div', { 'class': 'row' }).injectBottom(this.currentContainer);
for(var i = 1; i < 13; i++) {
var month = new Element('div', { 'html': lang[i - 1] }).injectBottom(row);
month.set('html', month.get('html').substr(0, 3)); //Setting and getting the innerHTML takes care of html entity problems (e.g. [M&a]uml;r => [Mär]z)
var iMonth = this.viewDate.clone().set('month', i - 1);
month.date = iMonth;
if(($defined(this.options.minDate) && this.format(this.options.minDate.clone().set('date', 1), '%t') > this.format(iMonth, '%t')) ||
($defined(this.options.maxDate) && this.format(this.options.maxDate.clone().set('date', 1), '%t') < this.format(iMonth, '%t')))
month.addClass('non-selectable');
else month.addEvent('click', this.levelDown.bind(this));
if(i - 1 == today.get('month') && this.viewDate.get('year') == today.get('year')) month.addClass('today');
if(i - 1 == this.selectedDate.get('month') && this.viewDate.get('year') == this.selectedDate.get('year')) month.addClass('selected');
if(!(i % 4) && i != 12) row = new Element('div', { 'class': 'row' }).injectBottom(this.currentContainer);
}
this.renderAfter();
},
renderDecade: function() {
this.label.removeClass('clickable');
this.view = 'decade';
this.currentContainer.addClass('year-decade');
var today = new Date();
var viewYear, startYear;
viewYear = startYear = this.viewDate.format('%Y').toInt();
while(startYear % 12) startYear--;
//Label
this.label.set('html', startYear +' '+ (startYear + 11));
var row = new Element('div', { 'class': 'row' }).injectBottom(this.currentContainer);
for(var i = startYear; i < startYear + 12; i++) {
var year = new Element('div', { 'html': i }).injectBottom(row);
var iYear = this.viewDate.clone().set('year', i);
year.date = iYear;
if(($defined(this.options.minDate) && this.options.minDate.get('year') > i) ||
($defined(this.options.maxDate) && this.options.maxDate.get('year') < i)) year.addClass('non-selectable');
else year.addEvent('click', this.levelDown.bind(this));
if(i == today.get('year')) year.addClass('today');
if(i == this.selectedDate.get('year')) year.addClass('selected');
if(!((i + 1) % 4) && i != startYear + 11) row = new Element('div', { 'class': 'row' }).injectBottom(this.currentContainer);
}
this.renderAfter();
},
renderAfter: function() {
//Iterate rows and add classes and remove navigation if nessesary
var rows = this.currentContainer.getElements('.row');
for(var i = 0; i < rows.length; i++) {
rows[i].set('class', 'row '+ ['a', 'b', 'c', 'd', 'e', 'f', 'g'][i] +' '+ (i % 2 ? 'even' : 'odd')).getFirst().addClass('first');
rows[i].getLast().addClass('last');
if(i == (this.view == 'month' ? 1 : 0) && $defined(this.options.minDate) && this.format(this.options.minDate, '%t') >= this.format(rows[i].getFirst().date, '%t'))
this.arrowLeft.setStyle('visibility', 'hidden');
if(i == rows.length - 1 && $defined(this.options.maxDate)) {
if((this.view == 'month' && this.format(this.options.maxDate, '%t') <= this.format(rows[i].getLast().date, '%t')) ||
(this.view == 'year' && this.format(this.options.maxDate, '%t') <= this.format(rows[i].getLast().date.clone().increment('month'), '%t')) ||
(this.view == 'decade' && this.format(this.options.maxDate, '%t') <= this.format(rows[i].getLast().date.clone().increment('year'), '%t')))
this.arrowRight.setStyle('visibility', 'hidden');
}
};
},
slideLeft: function() {
this.switchContainers();
//Render new view
switch(this.view) {
case 'month': this.viewDate.decrement('month'); break;
case 'year': this.viewDate.decrement('year'); break;
case 'decade': this.viewDate.set('year', this.viewDate.get('year') - 12); break;
}
this.render();
//Tween the new view in and old view out
this.currentContainer.set('tween', { 'duration': this.options.slideDuration, 'transition': this.options.slideTransition }).tween('left', [-this.currentContainer.getWidth(), 0]);
this.tempContainer.set('tween', { 'duration': this.options.slideDuration, 'transition': this.options.slideTransition }).tween('left', [0, this.tempContainer.getWidth()]);
},
slideRight: function() {
this.switchContainers();
//Render new view
switch(this.view) {
case 'month': this.viewDate.increment('month'); break;
case 'year': this.viewDate.increment('year'); break;
case 'decade': this.viewDate.set('year', this.viewDate.get('year') + 12); break;
}
this.render();
//Tween the new view in and old view out
this.currentContainer.set('tween', { 'duration': this.options.slideDuration, 'transition': this.options.slideTransition }).tween('left', [this.currentContainer.getWidth(), 0]);
this.tempContainer.set('tween', { 'duration': this.options.slideDuration, 'transition': this.options.slideTransition }).tween('left', [0, -this.currentContainer.getWidth()]);
},
levelDown: function(e) {
if(this.transitioning) return;
this.switchContainers();
this.viewDate = e.target.date;
//Render new view
switch(this.view) {
case 'year': this.renderMonth(); break;
case 'decade': this.renderYear(); break;
}
//Tween the new view in and old view out
this.transitioning = true;
this.currentContainer.set('tween', { 'duration': this.options.fadeDuration, 'transition': this.options.fadeTransition,
'onComplete': function() { this.transitioning = false }.bind(this) }).setStyles({'opacity': 0, 'left': 0}).fade('in');
this.tempContainer.set('tween', { 'duration': this.options.fadeDuration, 'transition': this.options.fadeTransition }).fade('out');
},
levelUp: function() {
if(this.view == 'decade' || this.transitioning) return;
this.switchContainers();
//Set viewdates and render
switch(this.view) {
case 'month': this.renderYear(); break;
case 'year': this.renderDecade(); break;
}
//Tween the new view in and old view out
this.transitioning = true;
this.currentContainer.set('tween', { 'duration': this.options.fadeDuration, 'transition': this.options.fadeTransition,
'onComplete': function() { this.transitioning = false }.bind(this) }).setStyles({'opacity': 0, 'left': 0}).fade('in');
this.tempContainer.set('tween', { 'duration': this.options.fadeDuration, 'transition': this.options.fadeTransition }).fade('out');
},
switchContainers: function() {
this.currentContainer = this.currentContainer.hasClass('a') ? this.element.getElement('.container.b') : this.element.getElement('.container.a');
this.tempContainer = this.tempContainer.hasClass('a') ? this.element.getElement('.container.b') : this.element.getElement('.container.a');
this.currentContainer.empty().removeClass('month').removeClass('year-decade').setStyles({ 'opacity': 1, 'display': 'block', 'z-index': 999 });
this.tempContainer.setStyle('z-index', 998);
this.label.addClass('clickable');
this.arrowLeft.setStyle('visibility', 'visible');
this.arrowRight.setStyle('visibility', 'visible');
},
pick: function(e) {
if($defined(e)) {
this.selectedDate = e.target.date;
this.element.getElements('.selected').removeClass('selected');
e.target.addClass('selected');
}
var value = this.format(this.selectedDate);
if(!this.options.injectInsideTarget) {
switch(this.target.get('tag')) {
case 'input': this.target.set('value', value); break;
default: this.target.set('html', value);
}
(this.hide.bind(this)).delay(150);
}
if($defined(this.hiddenInput)) this.hiddenInput.set('value', this.format(this.selectedDate, this.options.hiddenInputFormat));
this.options.pickFunction(this.selectedDate);
},
position: function() {
var top, left;
var coordinates = this.target.getCoordinates();
switch(this.options.alignX) {
case 'left':
left = coordinates.left;
break;
case 'middle':
left = coordinates.left + (coordinates.width / 2) - (this.element.getWidth() / 2);
break;
case 'right': default:
left = coordinates.left + coordinates.width;
}
switch(this.options.alignY) {
case 'bottom':
top = coordinates.top + coordinates.height;
break;
case 'top':
top = coordinates.top - this.element.getHeight();
break;
case 'ceiling': default:
top = coordinates.top;
}
left += this.options.offsetX.toInt();
top += this.options.offsetY.toInt();
this.element.setStyles({ 'top': top, 'left': left });
},
show: function() {
if(!this.visible & !this.options.alwaysShow) {
this.visible = true;
if(!Browser.Engine.trident) {
this.element.setStyles({ 'opacity': 0, 'display': 'block' });
if(!this.options.injectInsideTarget) this.position();
this.element.set('tween', { 'duration': this.options.toggleDuration, 'transition': this.options.fadeTransition }).fade('in');
} else {
this.element.setStyles({ 'opacity': 1, 'display': 'block' });
if(!this.options.injectInsideTarget) this.position();
}
}
},
hide: function() {
if(this.visible & !this.options.alwaysShow) {
this.visible = false;
if(!Browser.Engine.trident) {
this.element.set('tween', { 'duration': this.options.toggleDuration, 'transition': this.options.fadeTransition,
'onComplete': function() { this.element.setStyle('display', 'none') }.bind(this) }).fade('out');
} else this.element.setStyle('display', 'none');
}
},
toggle: function() {
if(this.visible) this.hide();
else this.show();
},
format: function(date, format) {
if(!$defined(format)) format = this.options.format;
if(!$defined(date)) return;
format = format.replace(/%([a-z%])/gi,
function($1, $2) {
switch($2) {
case 'D': return date.get('date');
case 'n': return date.get('mo') + 1;
case 't': return (date.getTime() / 1000).toInt();
}
return '%'+ $2;
}
);
return date.format(format);
},
outsideClick: function(e) {
if(this.visible) {
var elementCoords = this.element.getCoordinates();
var targetCoords = this.target.getCoordinates();
if(((e.page.x < elementCoords.left || e.page.x > (elementCoords.left + elementCoords.width)) ||
(e.page.y < elementCoords.top || e.page.y > (elementCoords.top + elementCoords.height))) &&
((e.page.x < targetCoords.left || e.page.x > (targetCoords.left + targetCoords.width)) ||
(e.page.y < targetCoords.top || e.page.y > (targetCoords.top + targetCoords.height))) ) this.hide();
}
},
//Version 1.0.1 addition, can easily be called from outside
setDate: function(value, pick) {
if(!$defined(pick)) pick = true;
if($type(value) == 'date') {
var date = value.clearTime();
} else {
var date = $chk(value) ? new Date().parse(this.target.get('value')).clearTime() : new Date().clearTime();
}
if(date.isValid()) {
this.selectedDate = date.clone();
this.viewDate = this.selectedDate.clone().set('date', 1);
this.render();
if(pick) this.pick();
}
}
});
Style.css is
.calendar-eightysix .body {
position: relative;
}
.calendar-eightysix .body .inner .container {
position: absolute;
left: 0;
}
In jquery replace the switchContainers: function() with
switchContainers: function() {
this.currentContainer = this.currentContainer.hasClass('a') ? this.element.getElement('.container.b') : this.element.getElement('.container.a');
this.tempContainer = this.tempContainer.hasClass('a') ? this.element.getElement('.container.b') : this.element.getElement('.container.a');
this.currentContainer.empty().removeClass('month').removeClass('year-decade').setStyles({ 'opacity': 1, 'display': 'block', 'z-index': 999 });
this.tempContainer.setStyles({ 'display': 'none', 'z-index': 998 });
this.currentContainer.hasClass('a') ? this.currentContainer.setStyles({ 'opacity': 1, 'display': 'block', 'z-index': 999 }) : '';
this.label.addClass('clickable');
this.arrowLeft.setStyle('visibility', 'visible');
this.arrowRight.setStyle('visibility', 'visible');
},
In style.css
Replace the .calendar-eightysix .body .inner .container with
.calendar-eightysix .body .inner .container {
left: 0;
}
I currently have the following highchart which display a start date and outputs the values for the next 31 days of data. Does anyone know how I may improve on this to include and end date so that I can filter the data by smaller specific amounts? On the x-axis I am also trying to only display labels that have data attached to them and hide any others. Any help is appreciated.
My code is as follows:
<script type="text/javascript">
var chart;
$(document).ready(function () {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: '<?php echo $type ?>',
x: -20 //center
},
xAxis: {
categories: [ <? php
$start = $_POST["dateStart"];
$dates = array();
for ($i = 0, $days = date('t', strtotime($start)); $i < $days; ++$i) {
$dates[] = date('Y-m-d', strtotime($start.' + '.$i.' day'));
}
echo "'".implode("', '", $dates)."'"; ?> ]
},
yAxis: {
title: {
text: 'Total Amount'
},
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: [ <? php
foreach($array as $legend = > $data) {
echo '{';
echo "name: '".$legend."',";
$values = array();
for ($i = 0; $i < $days; ++$i) {
$date = date('Y-m-d', strtotime($start.' + '.$i.' day'));
$values[] = isset($data[$date]) ? $data[$date] : 0;
}
echo 'data: ['.implode(', ', $values).'],';
echo '},';
} ?> ]
});
});
Thanks
Please note that the following IS NOT secure. You should ALWAYS run a sanity check on data submitted by the user.
xAxis: {
categories: [ <? php
$start = $_POST["dateStart"];
$end = $_POST["dateEnd"];
$dates = array();
$current=$start;
while($current<=$end){
$dates[]=$current;
$current=date('Y-m-d', strtotime($current.' + 1 day'));
}
echo "'".implode("', '", $dates)."'"; ?> ]
},