FullCalender 5 Unable to render dynamic events & resources - fullcalendar

I am trying to render events and resources which are stored in a database. I can get the calendar to render with predefined data for events and resources, however when I push data into the array's, the new objects do not appear when the calendar is rendered.
This is the JS code I am using to obtain the data and render the calendar;
function GetCalenderDetails() {
$.ajax({
url: 'myapiendpoint',
type: 'GET',
success: function (response) {
$.each(response.bookedServices, function (i, v) {
services.push({
id: v.id,
title: v.title
});
});
console.log(JSON.stringify(services));
$.each(response.userBookings, function (i, v) {
bookings.push({
id: v.id,
resourceId: v.resourceId,
title: v.title,
start: v.start,
allDay: v.allDayFlag
});
});
console.log(JSON.stringify(bookings));
calendar.render();
},
error: function (error) {
console.log(error);
}
});
}
var bookings = new Array({ id: '1', resourceId: 'a', title: 'Meeting', start: '2021-03-14', allDay: true });
var services = new Array({ id: 'a', title: 'Room A' });
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
schedulerLicenseKey: 'CC-Attribution-NonCommercial-NoDerivatives',
timeZone: 'UTC',
initialView: 'resourceTimelineDay',
aspectRatio: 1.5,
headerToolbar: {
left: 'prev,next',
center: 'title',
right: 'resourceTimelineDay,resourceTimelineWeek,resourceTimelineMonth'
},
editable: true,
resourceAreaHeaderContent: 'Resources',
resources: services,
events: bookings
});
GetCalenderDetails();
The following is the console output of the 'services' and 'bookings' variables after the GetCalenderDetails function is executed;
Resources Output
[{"id":"a","title":"Room A"},{"id":"b","title":"Room B"}]
Events Output
[{"id":"1","resourceId":"a","title":"Meeting","start":"2021-03-14","allDay":true},
{"id":"2","resourceId":"b","title":"Meeting B","start":"2021-03-15","allDay":true}]
The first resource and event will render, however the second item which is pushed into the array from the GetCalenderDetails function do not render.
I am probably missing something very obvious, but I am not seeing it, so another set of eyes might help :)

As suggested by ADyson's comments, here is the solution to my problem just in case anyone else ends up in the same position;
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
schedulerLicenseKey: 'CC-Attribution-NonCommercial-NoDerivatives',
timeZone: 'UTC',
initialView: 'resourceTimelineDay',
headerToolbar: {
left: 'prev,next,today',
center: 'title',
right: 'resourceTimelineDay,resourceTimelineWeek,resourceTimelineMonth'
},
editable: true,
resourceAreaHeaderContent: 'Booked Services',
resources: function (info, successCallback, failureCallback) {
$.ajax({
url: 'myapiendpoint',
type: 'GET',
success: function (response) {
var resources = [];
console.log(response);
if (response.status == true) {
$.each(response.bookedServices, function (i, v) {
resources.push({
id: v.id,
title: v.title
});
});
} else {
//Do something
}
return successCallback(resources);
},
error: function (error) {
console.log(error);
}
});
},
events: function (info, successCallback, failureCallback) {
$.ajax({
url: 'myapiendpoint',
type: 'GET',
success: function (response) {
var events = [];
console.log(response);
if (response.status == true) {
$.each(response.userBookings, function (i, v) {
events.push({
id: v.id,
title: v.title,
start: v.start,
allDay: v.allDayFlag
});
});
} else {
//Do something
}
return successCallback(events);
},
error: function (error) {
console.log(error);
}
});
}
});
calendar.render();

Related

timezone on full calendar is changing the time

I am trying full calendar for the first time on an ASP.NET MVC page. for the timezone, I have tried using 'local', 'America/Chicago'( as well as America/New_York and America/Los_Angeles) and variations of UTC all to no avail. When it has timezone: 'local' every event will show 2 hours after the start of each event, so an event at 11am will say 1pm. UTC is worse it is 8 hours off then. How do I fix this??
Here is the code
<script src="/Scripts/moment.js"></script>
<script src="/Scripts/fullcalendar.js"></script>
<script>
$(document).ready(function () {
$('#coverage').click(function () {
$('#Map').show();
});
$('#close').click(function () {
$('#Map').hide();
});
var events = [];
$.ajax({
type: "GET",
url: "/Home/GetEvents",
success: function (data) {
$.each(data, function (i, evt) {
events.push({
title: evt.Title,
start: evt.Start,
id: evt.ID
});
});
GenerateCalendar(events);
}
});
function GenerateCalendar(events) {
$('#calendar').fullCalendar('destroy');
$('#calendar').fullCalendar({
header: {
right: '',
center: '',
left: ''
},
theme: true,
timezone: 'local',
editable: false,
defaultDate: '#Convert.ToDateTime(ViewBag.EventDate).ToShortDateString() ',
allDaySlot: false,
selectable: true,
slotMinutes: 15,
events: events,
eventClick: function (calEvent) {
window.location = '/MonthlyEvents/Details/' + calEvent.id;
}
});
}
});
</script>

Fullcalendar with resources won't start on monday

For some reason, our Fullcalendar with resources does not want to start on monday, it always starts on the current day that we are. According to the docs, we should use firstDay, it also states that :
If weekNumberCalculation is set to 'ISO', this option defaults to 1 (Monday).
Which we did in our case, but no changes. We also tried upgrading to a different version (all above 5) but to no avail.
We are using version v5.11.3 of Fullcalendar (premium).
Anyone that can point us in the right direction?
In the screenshot that I've added, you can see it start on today (friday 18/11/2022).
var calendarEl = document.getElementById('calendar2');
var calendar = new FullCalendar.Calendar(calendarEl, {
schedulerLicenseKey: 'xxx',
timeZone: 'UTC',
initialView: 'resourceTimelineWeek',
hiddenDays: [0, 6],
locale: 'nl-be',
weekNumberCalculation: "ISO",
droppable: true,
eventStartEditable: false,
headerToolbar: {
left: 'prev,next',
center: 'title',
right: 'resourceTimelineDay,resourceTimelineWeek'
},
views: {
resourceTimelineWeek: {
duration: {days: 7},
slotDuration: '24:00:00',
buttonText: "Week",
},
resourceTimelineDay: {
duration: {days: 1},
slotDuration: '24:00:00',
buttonText: "Dag"
}
},
editable: true,
events: {
url: 'xxx.php',
type: 'POST',
error: function () {
alert('there was an error while fetching events!');
}
},
refetchResourcesOnNavigate: true,
resources: {
url: 'xxx.php',
type: 'POST',
error: function () {
alert('there was an error while fetching events!');
}
}, eventReceive: function (info) {
var resourceid = info.event._def.resourceIds[0];
var date = info.event._instance.range.start.toLocaleString();
var employeeid = info.draggedEl.dataset.employeeid;
$.ajax({
type: "POST",
url: "xxx.php",
cache: false,
data: {
'resourceid': resourceid,
'date': date,
'employeeid': employeeid
},
dataType: 'json',
success: function (data) {
var response = eval(data);
info.revert();
if (response.success) {
refetch();
}
}
});
}, eventContent: function (arg) {
let divEl = document.createElement('div');
let htmlTitle = arg.event._def.extendedProps.html;
divEl.innerHTML = htmlTitle;
let arrayOfDomNodes = [divEl];
return {domNodes: arrayOfDomNodes}
}
});
calendar.render();
function refetch() {
//direct refetch doesn't work
calendar.refetchEvents();
}

Jquery full calendar (style changes after page refresh)

This is my calendar initially after the event creation:
and this is after page refresh:
Can anyone help me understand how to keep the same style even after page refresh, specifically the vertical line in the middle? Sometimes the line increases as well.
The fullCalendar JS is as follows:
$('#calendar').fullCalendar({
locale: 'nl',
weekends: true, // false will hide Saturdays and Sundays
defaultView: 'agendaWeek',
allDaySlot: false,
slotLabelFormat: "HH:mm",
axisFormat: 'HH:mm',
timeFormat: 'HH:mm',
aspectRatio: 1,
editable: true,
eventStartEditable: true,
selectable: true,
selectHelper: true,
unselectAuto: false,
eventLimit: true,
dragScroll: true,
eventOverlap: false,
slotEventOverlap: false,
header: {
left: 'title',
center: '',
right: 'prev,next,today,agendaWeek,agendaDay'
},
views: {},
eventDrop: function (event, dayDelta, minuteDelta, allDay, revertFunc) {
var title = "Available";
var eventInfo;
eventInfo = {
title: title,
start: event.start,
end: event.end,
id: event.id
};
updateEvent(eventInfo);
},
eventResize: function (event, dayDelta, minuteDelta, revertFunc) {
var title = "Available";
var eventInfo;
eventInfo = {
title: title,
start: event.start,
end: event.end,
id: event.id
};
updateEvent(eventInfo);
},
select: function (start, end) {
var title = "Available";
var eventData;
if (title) {
eventData = {
title: title,
start: start,
end: end
};
$('#calendar').fullCalendar('renderEvent', eventData, true); // stick? = true
createEvent(eventData);
}
$('#calendar').fullCalendar('unselect');
},
eventSources: [{
events: function (start, end, timezone, callback) {
var employeeId = $("#employee-Id").val();
$.ajax({
url: '../' + employeeId + '/events',
dataType: 'json',
success: function (response) {
var events = $.parseJSON(response.data);
$('#calendar').fullCalendar('addEventSource', events);
callback(events);
}
});
}
}],
eventRender: function (event, element) {
//delete event on double click..Tanvir
element.one().bind('dblclick', function (e) {
/* e.preventDefault();
$(this).prop('disabled', true);
setTimeout(function () { $(this).prop('disabled', false); }, 500);*/
$("#startTime").html(moment(event.start).format('MMM Do YYYY, h:mm A'));
$("#endTime").html(moment(event.end).format('MMM Do YYYY,h:mm A'));
$("#eventContent").dialog({modal: true, title: event.title, width: 100});
$('.delete-event').bind('click', function (e) {
$('#calendar').fullCalendar('removeEvents', event._id);
deleteEvent(event.id);
$("#eventContent").hide();
});
$('.discard-delete').bind('click', function () {
$("#eventContent").hide();
});
});
},
});
});
No duplicate event is created in the database. What is happening a the event HTML is rendering twice after refresh. Specifically fc-time-grid-event under the event container class is rendering twice after refresh.
The cause of the duplication is here, in your events function:
$('#calendar').fullCalendar('addEventSource', events);
callback(events);
You are adding the event objects as an event source, AND sending them back to the calendar as a list of events, in the documented way. So while the events may not be duplicated in your database, your code is sending two sets of identical event data to the calendar, and consequently they are displayed twice.
You can simply remove this line:
$('#calendar').fullCalendar('addEventSource', events);
as it is totally unnecessary in this context.

fullcalendar - multiple sources to turn off and on

I've a calendar that I want to list various types of event on and enable a checkbox filter to show/hide those kind of events.
Is there a way to say on this action, ONLY load from 1 data-source AND remember that URL on month next/prev links?
I've started using eventSources, but it loads them all, rather than the one(s) I want.. Here's what I have.
var fcSources = {
all: {
url: tournament_url + '/getCalendar/?typefilter=[1,2]'
},
type1: {
url: tournament_url + '/getCalendar/?typefilter=[1]'
},
type2: {
url: tournament_url + '/getCalendar/?typefilter=[2]'
}
};
These URLS all provide a json string of events, based on the types prrovided.
Here's my calendar:
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek'
},
firstDay: 1, // Monday = 1
defaultDate: new Date(), // Now
editable: true,
eventSources: [ fcSources.all ],
events: fcSources.all,
nextDayThreshold: '00:00:00',
... etc etc
Above my calendar I have this:
input type="checkbox" name="event_filter[]" value="type1" /> Type 1
input type="checkbox" name="event_filter[]" value="type2" /> Type 2
And finally , two Jquery fucntions.. one to get all the filters:
function getFilters(getName) {
var filters = [];
var checked = [];
$("input[name='"+getName+"[]']").each(function () {
filters.push( $(this).val() );
});
$("input[name='"+getName+"[]']:checked").each(function () {
checked.push( $(this).val() );
});
return [filters, checked];
}
and the last to load them:
$(".event_filter").on('click', function() {
var doFilters = getFilters('event_filter');
$('#calendar').fullCalendar( 'removeEvents' );
if (doFilters[0] === doFilters[1]) {
$('#calendar').fullCalendar( 'addEventSource', fcSources.all );
} else {
$.each(doFilters[1], function(myFilter, myVal) {
console.log(myVal);
$('#calendar').fullCalendar( 'addEventSource', fcSources.myVal );
});
}
// $('#calendar').fullCalendar( 'refetchEvents' );
});
Since the sources are all the same place and just different data on the URL, this approach could meet your needs. In the demo it just alerts the URL that is being tried but doesn't actually supply any data...
https://jsfiddle.net/gzbrc2h6/1/
var tournament_url = 'https://www.example.com/'
$('#calendar').fullCalendar({
events: {
url: tournament_url + '/getCalendar/',
data: function() {
var vals = [];
// Are the [ and ] needed in the url? If not, remove them here
// This could (should!) also be set to all input[name='event_filter[]'] val's instead of hard-coded...
var filterVal = '[1,2]';
$('input[name="event_filter[]"]:checked').each(function() {
vals.push($(this).val());
});
if (vals.length) {
filterVal = '[' + vals.join(',') + ']' // Are the [ and ] needed in the url? If not, remove here too
}
return {
typefilter: filterVal
};
},
beforeSend: function(jqXHR, settings) {
alert(unescape(settings.url));
}
}
});
// when they change the checkboxes, refresh calendar
$('input[name="event_filter[]"]').on('change', function() {
$('#calendar').fullCalendar('refetchEvents');
});
Try this!
$('#calendar').fullCalendar({
events: function( start, end, timezone, callback ) {
var checked = [];
$("input[name='event_filter[]']:checked").each(function () {
checked.push( $(this).val() );
});
var tournament_url = 'https://www.example.com';
$.ajax({
url: tournament_url + '/getCalendar/',
data: {typefilter: '['+checked.join(',')+']'},
success: function(events) {
callback(events);
}
});
}
});
$('input[name="event_filter[]"]').on('change', function() {
$('#calendar').fullCalendar('refetchEvents');
});
This works for me.

Populate FullCalendar eventsources with webmethod json feed in ASP.NET?

How can I consume a JSON feed? The webmethod gets hit, but it throwns the error, "error while fetching events." I think its related to ASP.NET wrapping everything with "d." but I don't know how to proceed.
[WebMethod]
public string GetEvents(string webMethodParam)
{
return #"[{""title"": ""All Day Event"",""start"": ""2014-09-01""}]";
}
function createCal() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
eventSources: [{
url: "<%= AdminPath %>WebMethods/WebService1.asmx/GetEvents",
type: 'POST',
data: {
webMethodParam: 'something'
},
error: function () {
alert('there was an error while fetching events!');
}
}],
defaultDate: '2014-09-12',
editable: false,
eventLimit: true
});
}
It was related to this weird "d." wrapper. To fix it I did the following.
[WebMethod]
public void GetEvents(string webMethodParam)
{
string ret = #"[{""title"": ""All Day Event"",""start"": ""2014-09-01""}]";
this.Context.Response.ContentType = "application/json; charset=utf-8";
this.Context.Response.Write(ret);
}
To create the calendar to async call the webmethod with the current date, I did this.
function getCalendarDisplayDate() {
try {
var now = moment().format("dddd, MMMM Do, YYYY, h:MM:ss A");
var m = moment();
var moment2 = $('#calendar').fullCalendar('getDate');
return moment2.format();
}
catch (err) {
}
return "init";
}
function createCal() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
eventSources: [{
url: "<%= AdminPath %>WebMethods/WebService1.asmx/GetEvents",
type: 'POST',
data: {
webMethodParam: getCalendarDisplayDate
},
error: function (v) {
alert('there was an error while fetching events!');
}
}],
defaultDate: '2014-09-12',
editable: false,
eventLimit: true
});
}

Resources