I have a couple of FullCalendar instances each in its own Tab.
At first when I switched tabs, the calendars did not display, so I added this part to render the calendars once you click on a tab
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
var redrawcal = $(this).attr('href');
redrawcal = redrawcal.substring(1,redrawcal.length);
$('#calendar_'+redrawcal).fullCalendar('render');
$('.fc-today').removeClass('fc-today');
});
This works perfectly for each tab after the first, however, the first Tab's calendar's event times are incorrect.
As shown in the image below, the second tab's events are correct:
But The first tab does not rerender the events correct, the initial placement and the placement if you switch tabs are exactly the same, as seen in the image below:
I have the following code that's suppose to render the calendar after it has been created at first:
$(function(){
//first tab's calander is not rendering correctly, this will make it show correct from the start
<?php $branch = $branches[0]; ?>
<?php $branch_studio_id = str_replace(" ", "_", $branch['branch_studio_name']); ?>
<?php $branch_studio_id = preg_replace("/[^a-zA-Z]/", "", $branch_studio_id); ?>
$('#calendar_<?= $branch_studio_id; ?>').fullCalendar('render');
});
For this example, the calendar's id is calendar_Centurion, the PHP simply removes spaces and special characters
I have also tried this:
$('#calendar_<?= $branch_studio_id; ?>').fullCalendar('rerenderEvents');
But I still have the same results.
The two events in the two calendars have exactly the same times on the same day, and all information is the same
If there is only one Tab, it is broken without an extra tab to rerender the calendar.
I have basically tries everything that I could find and that I could think of that might help but with no positive results.
Unfortunately I cannot create a fiddle of this as it would take quite long to do so and the actual code/project is not open to the public as of yet.
I do hope this can be easily solved.
Thanx in advance!
UPDATE
Below is the HTML and JS code for my calendars
<?php $branch_studio_id = str_replace(" ", "_", trim($branch['branch_studio_name'])); ?>
<?php $branch_studio_id = preg_replace("/[^a-zA-Z]/", "", $branch_studio_id); ?>
<div class="tab-pane <?=($x == 1) ? 'active' : '' ?>" id="<?=$branch_studio_id ?>">
<div class="row">
<div class="col-md-9">
<div id="calendar_<?= $branch_studio_id ?>"></div>
</div>
<div class="col-md-3">
<p class="h4 text-light">Classes not on timetable</p>
<hr />
<div id='external-events_<?=$branch_studio_id ?>'>
<?php foreach ($classes_notimetable as $class) :?>
<?php if ($class['studio_id'] == $branch['studio_id']) : ?>
<div class="external-event label label-success" data-event-class="fc-event-success" data-class-id="<?=$class['id']?>"><?=$class['class_name'] ?></div>
<?php endif;?>
<?php endforeach;?>
<hr />
</div>
</div>
</div>
</div>
<script type="text/javascript">
(function($) {
'use strict';
var initCalendarDragNDrop<?=$x;?> = function() {
$('#external-events_<?=$branch_studio_id ?> div.external-event').each(function() {
// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
// it doesn't need to have a start or end
var eventObject<?=$x;?> = {
title : $.trim($(this).text()), // use the element's text as the event title
};
// store the Event Object in the DOM element so we can get to it later
$(this).data('eventObject', eventObject<?=$x;?>);
// make the event draggable using jQuery UI
$(this).draggable({
zIndex : 999,
revert : true,
revertDuration:0
});
});
};
var initCalendar<?=$x;?> = function() {
var $calendar<?=$x;?> = $('#calendar_<?=$branch_studio_id ?>');
var date = new Date();
var daynum = date.getDay();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$calendar<?=$x;?>.fullCalendar({
header: {left: '', center: '', right: ''},
defaultView: 'agendaWeek',
timeFormat: 'HH:mm',
slotDuration: '00:10:00',
snapDuration: '00:05:00',
firstDay : 1,
columnFormat: 'ddd',
minTime:'<?= (isset($school_custom['school_from_hour'])) ? $school_custom['school_from_hour'] : '08'; ?>:<?= (isset($school_custom['school_from_minutes'])) ? $school_custom['school_from_minutes'] : '00'; ?>',
maxTime: '<?= (isset($school_custom['school_to_hour'])) ? $school_custom['school_to_hour'] : '21'; ?>:<?= (isset($school_custom['school_to_minutes'])) ? $school_custom['school_to_minutes'] : '00'; ?>',
allDaySlot: false,
defaultTimedEventDuration: '01:00:00',
forceEventDuration:true,
editable : true,
eventDrop: function(event) {
var eventid = event.id;
var eventday = (event.start._d).getDay();
var eventstarthour = (event.start._d).getHours()-2;
var eventstartminute = (event.start._d).getMinutes();
var eventendhour = (event.end._d).getHours()-2;
var eventendminute = (event.end._d).getMinutes();
$('').postJsonCheck('classes/update_class_times', {event_id: eventid, event_day:eventday, event_starthour:eventstarthour,event_startminute:eventstartminute,event_endhour:eventendhour,event_endminute:eventendminute}, function(data){
});
},
droppable : true, // this allows things to be dropped onto the calendar !!!
drop : function(date) {// this function is called when something is dropped
var $externalEvent = $(this);
// retrieve the dropped element's stored Event Object
var originalEventObject = $externalEvent.data('eventObject');
// we need to copy it, so that multiple events don't have a reference to the same object
var copiedEventObject = $.extend({}, originalEventObject);
// assign it the date that was reported
copiedEventObject.start = date;
//copiedEventObject.allDay = allDay;
copiedEventObject.className = $externalEvent.attr('data-event-class');
var classid = parseInt($(this).attr('data-class-id'));
copiedEventObject.id = classid;
// render the event on the calendar
// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
$('#calendar_<?=$branch_studio_id ?>').fullCalendar('renderEvent', copiedEventObject, true);
//Update DB
var eventday = (copiedEventObject.start._d).getDay();
var eventstarthour = (copiedEventObject.start._d).getHours()-2;
var eventstartminute = (copiedEventObject.start._d).getMinutes();
var eventendhour = (copiedEventObject.start._d).getHours()-1;
var eventendminute = (copiedEventObject.start._d).getMinutes();
$('').postJsonCheck('classes/add_class_timetable', {class_id: classid, event_day:eventday, event_starthour:eventstarthour,event_startminute:eventstartminute,event_endhour:eventendhour,event_endminute:eventendminute}, function(data){
});
//remove the event from the not on timbetable list
$(this).remove();
},
eventResize: function(event, delta, revertFunc) {
var classid = event.id;
var eventendhour = (event.end._d).getHours()-2;
var eventendminute = (event.end._d).getMinutes();
$('').postJsonCheck('classes/update_class_duration', {class_id: classid, event_endhour:eventendhour,event_endminute:eventendminute}, function(data){
});
},
events : [<?php $z = 0;?>
<?php foreach ($classes as $class): ?>
<?php $z++;?>
<?php if ($class['studio_id'] == $branch['studio_id']) : ?>
{
id: <?=$class["day_id"]?>,
title: '<?=$class["class_name"]?>',
start: new Date(y, m, d-(daynum-<?=$class["day"]?>), '<?=$class["start_hour"]?>', '<?=$class["start_minute"]?>'),
end: new Date(y, m, d-(daynum-<?=$class["day"]?>), '<?=$class["end_hour"]?>', '<?=$class["end_minute"]?>')
}
<?php if ($z < count($classes))echo ","?>
<?php endif;?>
<?php endforeach; ?>]
});
};
$(function() {
initCalendar<?=$x;?>();
initCalendarDragNDrop<?=$x;?>();
});
}).apply($(this), [jQuery]);
</script>
*Please note that there is a php foreach loop outside of the above code, so this code gets duplicated for each calendar, each with a unique $branch_studio_id used in the calendar's ID
Related
I have a site that imports a .ics file, saves the information to a table and I am looking to display the events on my fullCalendar.
Here is the code that produces the $events json Object
<?php
$sqlquery2 = db_query("select * from events");
while($eventRow = mysqli_fetch_array($sqlquery2)) {
//$events[] = array(); //Adds the 1st event only
$events = []; //Adds the last event only
array_push($events, json_encode([
'title' => $eventRow['League'],
'start' => $eventRow['StartDate']
]));
foreach($events as $events => $value){
print $value;
}
}
?>
I am able to get this to print a response for each of the (3) rows in my table:
{"title":"GLVC Noncon (D2) Baseball","start":"2023-02-24"}{"title":"GLVC Noncon (D2) Baseball","start":"2023-02-25"}{"title":"MVC Con (D1) Baseball","start":"2023-03-31"}
The problem I have is when adding events to the calendar in my javascript...It adds only the 1st event if I declare $events[] = array(); but only adds the LAST event if I declare $events = [];
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function(){
var eventsJS = new Array();
var eventsJS = <?php print $value;?>;
console.log(eventsJS);
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
headerToolbar: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth timeGridWeek listWeek'
},
initialView: 'dayGridMonth',
events: [eventsJS]
});
calendar.render();
});
</script>
It appears that my variable $events is getting overwritten, but I cannot figure out why or how to stop it from happening!
I have tried using forEach and various looping functions, but I think I have what I need, just need to know why my variable is getting overwritten.
Calendar with 1 event, but 3 objects returned
I use Pickadate.js and JQuery Form Plugin. I have date and time pickers seperately. What I want to do is to disable times in timepicker according to value of datepicker. So, I am trying to get the JSON data into picker.set("disable", [ ]);. I can console.log the plain text but it remains aimless.
I tried a lot and have come across these solutions in that question. But I couldn't launch them. (I adapted pickadate functions and classes to pickatime's.)
// Javascript
$(document).ready(function() {
$("input").click(function() {
$(".datepicker").pickadate({
format: 'yyyy-mm-dd',
formatSubmit: 'yyyy-mm-dd',
min: true,
max: false
});
var $input = $(".timepicker").pickatime({
format: 'HH:i',
formatSubmit: 'HH:i',
formatLabel: 'HH:i'
});
$('.datepicker').change(function() {
$('#form').ajaxSubmit({
target: '#check_result',
url: 'check.php',
success: function showResponse(responseText, $form) {
var picker = $input.pickatime('picker');
picker.set("disable", [
console.log(responseText)
]);
}
});
return false;
});
});
});
// PHP (check.php)
<?php
// Database connection done.
$date = mysqli_real_escape_string($con, $_POST['date']);
$match_query = mysqli_query($con, "SELECT * FROM booking WHERE DATE(time) = '$date'");
$disabled_times = array();
if ($result = $match_query) {
while ($row = mysqli_fetch_assoc($result)) {
$disabled_times[] = $row['time'];
}
mysqli_free_result($result);
}
echo implode($disabled_times);
?>
Can you post an example of the json being returned from your php?
According to the docs (http://amsul.ca/pickadate.js/api/#method-get-disable)
your json should be something like this: [2,30], [4,30], [9,0]
If your json is correct, be sure it is not being passed to the timepicker as a string. Try something like:
var json = JSON.parse(responseText);
picker.set("disable", [ json ]);
UPDATE:
I guess with the following code, your json will return properly:
...
$time = explode(',', $row['time']);
$time[0] = (int)$time[0];
$time[1] = (int)$time[1];
$disabled_times[] = $time;
...
echo json_encode($disabled_times);
I am using mySQL to store information about check-out dates, and then depending on the object I would like to display the times that are already taken with FullCalendar.js
I am using PHP to pull in rows and then loop through them populating the where events are created, the code looks right when I check it on the page, but data is not loaded.
Here is the code generating the page:
function getAllTimes(){
if(!empty($_GET['id']))
{
$query = "
SELECT userID, startDate, endDate
FROM checkout
Where equID =" .$_GET['id'];
global $db;
$stmt = $db->prepare($query);
$stmt->execute();
$rows = $stmt->fetchAll();
echo "<script type=\"text/javascript\">
$(document).ready(function() {
$('#calendar').fullCalendar({
events: [";
$counter = 0;
foreach($rows as $row):
if($counter == 0)
{
echo "
{
title : '".$row['userID']."',
start : '".$row['startDate']."',
end : '".$row['endDate']."'
}";
$counter = $counter+1;
}
else
{
echo ",
{
title : '".$row['userID'].",'
start : '".$row['startDate'].",'
end : '".$row['endDate']."'
}";
$counter = $counter+1;
}
endforeach;
echo "
]
});
}}";
echo "
</script>";
}
else
echo "ID must be specified";
}
getAllTimes();
And this is the outcome when loaded, yet events are not added to the calendar.
<script type="text/javascript">
$(document).ready(function() {
$('#calendar').fullCalendar({
events: [
{
title : 'ArtemBeer',
start : '2014-01-16 00:00:00',
end : '2014-01-16 00:00:00'
},
{
title : 'ArtemBeer,'
start : '2014-01-15 00:00:00,'
end : '2014-01-16 00:00:00'
},
{
title : 'ArtemBeer,'
start : '2014-01-09 02:02:00,'
end : '2014-01-10 03:03:00'
}
]
});
}}
</script>
Your data (JS) has a bad comma:
start : '2014-01-15 00:00:00,'
should be:
start : '2014-01-15 00:00:00',
Also use your Chrome Inspector to see JS errors via the console, otherwise you will be guessing all day long.
I have a JQuery calendar plugin I'm using currently and as of right now I'm stuck on trying to figure out how to populate the calendar with information from a PHP file using AJAX.
var Script = function () {
// calendar
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
/*---------------------------------------------------------------------------*/
window.onload = function myfunction() {
var xmlhttp;
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest;
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("calendar").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "../ajax/calendar.php", true);
xmlhttp.send();
}
/*---------------------------------------------------------------------------*/
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
editable: false,
events: [
{
title: 'Lunch',
start: new Date(y, m, d, 12, 0),
end: new Date(y, m, d, 14, 0),
allDay: false
},
]
});
}();
This is the PHP File
<?
$query = mysql_query("SELECT * FROM table WHERE id = '1093'");
do {
$message = $row['message'];
$hour = $row['hour'];
$minute = $row['minute'];
$year = $row['year'];
$month = $row['month'];
$day = $row['day'];
$status = $row['status'];
if(eregi('pending', $status)) {
echo '
{<br>
title: '.$message.',<br>
start: new Date('.$year.', '.$month.', '.$day.', 12, 0),<br>
end: new Date('.$year.', '.$month.', '.$day.', 14, 0),<br>
allDay: false<br>
},
';
}
}while($row = mysql_fetch_array($query));
} else header('location: error.php');
?>
How do I get the info from my database table to loop into my JQuery plugin?
PHP have a json_encode() method allowing you to convert PHP arrays to valid JSON objects.
Also make sure to output the correct content-type header.
header('Content-Type: application/json');
echo json_encode($my_datas_from_DB);
Just output your content with this method so it can be consumed by JavaScript.
(Side note: JSON is not HTML, <br> wouldn't be valid here as you try to output JSON manually)
It's much easier than you think, you can define your events property as an ajax call like so (right in your fullcalendar initialization):
...
events: {
url: '../phpPath/pathToEventScript.php',
dataType: 'json',
type: "POST"
},
...
just be sure that each event object (in your array of objects) has a start property.
PHP script:
$select = "SELECT title, start FROM events";
$stmt = $db->query($select);
$events = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($events);
Do something like this:
"your.js" could be something like this:
$.get( "../ajax/calendar.php", function( data ) {
$('#calendar').fullCalendar(eval("(" + data + ")"))
alert( "Calendar initilazed ;)" );
});
and your php file havenot to include "< br >" tag as new line!
I use ExtJS 1.0.1 (in magento)
I would like to get all checked nodes on form submit. And I stucked here:
tree.html (initialization):
tree<?php echo $this->getId() ?> = new Ext.tree.TreePanel.Enhanced('<?php echo $_divId ?>', {
animate: false,
loader: categoryLoader,
enableDD: false,
containerScroll: true,
rootVisible: '<?php echo $this->getRoot()->getIsVisible() ?>',
useAjax: true,
currentNodeId: <?php echo (int) $this->getCategoryId() ?>,
addNodeTo: false
});
On submit function:
function submit()
{
console.log(tree'.$this->getId().');
// got html code <div id="treeoptions_fieldset992cb0dd9a7da511e5596a229a5386d5_select_catalogb0f2cd4faa4f13b72f0df314bdc222ec" class="tree x-tree"><ul class="x-tree-root-ct x-tree-lines" id="ext-gen5859">...</ul></div>
var checked_nodes = tree'.$this->getId().'.getChecked();
// got an error Uncaught TypeError: Object #<HTMLDivElement> has no method 'getChecked'
}
Magento uses prototypeJS in admin panel.
The question is how to address to checked_nodes to run getChecked()?
Based on some Googling on the Tree function of EXTJS try this
var checked_nodes = tree'.$this->getId().'.select(".x-grid-row-selected");
console.log(checked_nodes);
the .select() method finds all the children nodes that match the selected CSS selector
get works!
I created the object after treegetId() ?> init:
function av_OkButton()
{
var tree = null;
this.onPress = function()
{
var ids = this.tree.getChecked();
}
this.getTree = function()
{
return this.tree;
}
this.setTree = function(treeObj)
{
this.tree = treeObj;
return this;
}
}
okButton = new av_OkButton;
okButton.setTree(tree<?php echo $this->getId() ?>);
And then created submit button:
Cannot understand what the difference between I did and what I have now but it works for me