add custom params to fullcalendar request - javascript

I'm want to add a parameter named foo to the request that fullcalendar submits when retrieving event data. According to the docs this can be achieved using:
var getFoo() = function() {
// implementation omitted
};
$('#calendar').fullCalendar({
loading: function(isLoading) {
// CAN I SOMEHOW UPDATE foo FROM HERE?
},
events: {
url: '/myfeed.php',
type: 'POST',
data: {
foo: getFoo()
}
}
});
I want the value of the foo parameter to be calculated each time the calendar event data is requested, but it seems that fullcalendar only calls getFoo() the first time it loads, then re-uses that value for each subsequent request.
I've tried using this the loading event that is triggered immediately before the data is loaded, but I can't figure out how to update the foo paramter from within this function.
Update
I followed the advice below and got it working with this:
$('#calendar').fullCalendar({
events: function(start, end, callback) {
$.ajax({
url: 'getCalendarEvents',
dataType: 'json',
data: {
start: Math.round(start.getTime() / 1000),
end: Math.round(end.getTime() / 1000),
foo: getFoo()
},
success: function(doc) {
var events = eval(doc);
callback(events);
}
});
},
});

Maybe you could use the events as function to create your own ajax request.
var getFoo() = function() {
// implementation omitted
};
$('#calendar').fullCalendar({
events: function(start, end, callback) {
var myFoo = getFoo();
$.ajax({
url: 'myxmlfeed.php',
dataType: 'xml',
data: {
// our hypothetical feed requires UNIX timestamps
start: Math.round(start.getTime() / 1000),
end: Math.round(end.getTime() / 1000),
foo: myFoo
},
success: function(doc) {
var events = [];
$(doc).find('event').each(function() {
events.push({
title: $(this).attr('title'),
start: $(this).attr('start') // will be parsed
});
});
callback(events);
}
});
}
});

Try setting lazyFetching to false. I'm guessing you're having this problem because fullCalendar tries to save you from unnecessary ajax requests.
Fullcalendar doc on lazyFetching

Related

Full calendar resource extra params not added

I try to customize the params that send with the events and resources on the fullCalendar library.
I use full calendar version 3.
I can fetch these custom params from a form and assign them to events request.
But the issue is with resources that I use the same code for both but the requested URL for resource breaks and also lost the default start and end prams as well.
The code that I tried:
resources: {
// Resource route to load Instructors.
url: resourcesCallback,
method: 'GET',
data: function() {
var fields = jQuery('.calendar_filter_form').serializeArray();
var datas = {};
jQuery.each(fields, function(index, val) {
/* iterate through array or object */
datas[val.name] = val.value;
});
return datas;
},
failure: function() {
alert('There was an error while fetching instructors!');
},
},
and the event part:
events: {
// Resource route to load Instractors.
url: eventsCallback,
method: 'GET',
data: function() {
var fields = jQuery('.calendar_filter_form').serializeArray();
var data = {};
jQuery.each(fields, function(index, val) {
/* iterate through array or object */
data[val.name] = val.value;
});
return data;
},
failure: function() {
alert('there was an error while fetching events!');
},
}
The generated URL that I get are these:
For events:
Request URL: DOMAIN/load?instractor=&lessonType=&date=&start=2019-07-22T00%3A00%3A00&end=2019-07-23T00%3A00%3A00&_=156377682
For resources:
Request URL: DOMAIN/resources?_=1563776826863
I need to generate the second URL like the first, as you see the code is same but result is different, what is wrong?
The full code if needed:
$('#calendar').fullCalendar({
defaultView: 'agendaDay',
// Active the ajax reload the resources(instructors).
refetchResourcesOnNavigate: true,
// To make the time slot divided in 15mis.
slotDuration: "00:15:00",
displayEventTime : false,
// This define each time slot can get how many part
// of the rows, for example if we set it to "00:01:00"
// then it will divide each row by 15 mins but just show
// the one between one like: 00:15:00 , 00:45:00 , 01:15:00.
slotLabelInterval: "00:01:00",
slotLabelFormat: ['H:mm'],
groupByResource: true,
// To trun of the all day row at the top of calendar.
allDaySlot: false,
groupByDateAndResource: true,
// Settings for manage the calendar header options.
header: {
left: 'prev, today, next',
center: 'title',
right: null,
},
eventRender: function (event, $element) {
// Render the Main content of the events with more details
// and with html tags to be more user friendly.
$element.find('.fc-title').html('<p style="text-align:center">'
+ event.lessonType + ' ~ ' + event.student
+ '<br>' + event.description
+ '<br>' + event.lessonAvailable + '~' + event.nextEvent + '</p>'
);
},
// Define the Calendar column name.
// This part should be dynamic and will
// define by instructor names.
resources: {
// Resource route to load Instructors.
url: resourcesCallback,
method: 'GET',
data: function() {
var fields = jQuery('.calendar_filter_form').serializeArray();
var data = {};
jQuery.each(fields, function(index, val) {
/* iterate through array or object */
data[val.name] = val.value;
});
return data;
},
failure: function() {
alert('There was an error while fetching instructors!');
},
},
// The main part of getting data and manipulate them
// to show those in proper format in the calendar.
// To match with resources here the resourceId should match
// with the ids that provided in the resources.
// Also to get proper location according to time slot
// it need the correct start and end params that should
// be in correct date format like: 2019-07-18T19:30:00.
events: {
// Resource route to load instructors.
url: eventsCallback,
method: 'GET',
data: function() {
var fields = jQuery('.calendar_filter_form').serializeArray();
var datas = {};
jQuery.each(fields, function(index, val) {
/* iterate through array or object */
datas[val.name] = val.value;
});
return datas;
},
failure: function() {
alert('there was an error while fetching events!');
},
}
});
In the meantime, of course, the obvious workaround is to use the resources-as-function pattern instead, then you can construct the AJAX request exactly as you need it.
Thanks, #ADyson.
resources: function(callback){
jQuery('input[name="start"]').val(jQuery('#calendar').fullCalendar('getView').start.format());
jQuery('input[name="end"]').val(jQuery('#calendar').fullCalendar('getView').end.format());
jQuery.ajax({
url: resourcesCallback,
type: 'GET',
dataType: "json",
data: jQuery('.calendar_filter_form').serialize(),
error: function() {
// alert('Oops! Try again.');
},
success: function(response){
callback(response);
}
});
},

Show events in fullcalendar using ajax

I am writing application on asp.net core 2.0. and trying to show events stored in DB in calendar. I have added links to js and css files as it is shown in documentation. As event source I am using events as function as it is shown in official documentation Fullcalendar Doc but my calendar does not show events. It is empty!
GetEvents method in Schedules controller which gets data from DB
public ActionResult GetEvents()
{
return new JsonResult(Json(from events in _context.Schedules
select new { id = events.ID,
EventTitle = events.EmployeeID,
ShiftDate = events.ShiftDate.Date } ));
}
I also tried to modify ajax but it also does not work.
<div id="calendar"></div>
<script>
$(document).ready(function () {
$('#calendar').fullCalendar({
events: function (start, end, timezone, callback) {
$.ajax({
url: "/Schedules/GetEvents",
type: "POST",
dataType: "JSON",
success: function (result) {
var eventsList = [];
// alert(result); // --1--
// alert(JSON.stringify(result)); // --2--
$(result).each(function () {
var eventTitle = $(this).attr('EventTitle');
var eventStart = $(this).attr('ShiftDate');
var eventId = $(this).attr('id');
eventsList.push(
{
id: eventId,
title: eventTitle,
start: eventStart
});
});
if (callback)
callback(eventsList);
}
});
}
});
});
</script>
First alert shows message [Object object]..., Second alert shows all selected data in a "JSON string". But calendar does not show anything.
So, what am I doing wrong? Thank you!
Try this:
result.forEach(function (item) {
eventsList.push({
id: item.id, title: item.EventTitle, start: item.ShiftDate
})
})

FullCalendar - Events gets data from API and seems correct, but not displayed in calendar

First or all.. i have browsed through tons of material and examples on this, but i cannot figure it out eitherhow..
Scenario :
Running on ASP.NET using Web Api 2...
API is called to fetch events, objects seems legit :
Issue seems to be that callback is never true..
Code :
$(document).ready(function() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var calendar = $('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
selectable: true,
selectHelper: true,
select: function (start, end, allDay) {
var title = prompt('Event Title:');
if (title) {
calendar.fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
allDay: allDay
},
true // make the event "stick"
);
}
calendar.fullCalendar('unselect');
},
editable: true,
events: function (start, end, callback) {
$.ajax({
type: "GET", //WebMethods will not allow GET
url: "api/Calendar/GetCalendarEvents/" + getQueryVariable("teamid"),
//completely take out 'data:' line if you don't want to pass to webmethod - Important to also change webmethod to not accept any parameters
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (doc) {
var events = []; //javascript event object created here
var obj = doc;
$(obj).each(function () {
events.push({
title: $(this).attr('title'), //your calevent object has identical parameters 'title', 'start', ect, so this will work
start: $(this).attr('start'), // will be parsed into DateTime object
end: $(this).attr('end'),
id: $(this).attr('id')
});
});
if (callback) callback(events);
}
});
}
});
According to the official doc https://fullcalendar.io/docs/event_data/events_function/, function for programmatically generating Event Objects
function( start, end, timezone, callback ) { }
You should replace your events function with this:
events: function (start, end, timezone, callback) {
$.ajax({
type: "GET", //WebMethods will not allow GET
url: "api/Calendar/GetCalendarEvents/" + getQueryVariable("teamid"),
//completely take out 'data:' line if you don't want to pass to webmethod - Important to also change webmethod to not accept any parameters
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (doc) {
var events = []; //javascript event object created here
var obj = doc;
$(obj).each(function () {
events.push({
title: $(this).attr('title'), //your calevent object has identical parameters 'title', 'start', ect, so this will work
start: $(this).attr('start'), // will be parsed into DateTime object
end: $(this).attr('end'),
id: $(this).attr('id')
});
});
if (callback) callback(events);
}
});
}
Because when you are calling with three parameters, fourth param callback is empty, that's the reason of not getting events.

Fullcalendar not rendering events

I have this code that creates an array of event objects, which is then passed into the calendar, but for some reason the calendar does not render the events.
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'title',
center: '',
right: 'prev,next'
},
editable: true,
eventLimit: true,
events: function(start, end, timezone, callback) {
$.ajax({
success: function(doc) {
var events = [];
$.getJSON('../php/logg.php', function(data) {
$.each(data, function(key, val){
var temp = moment($(this).attr('dato'))
if(temp.isBefore(start)){ return true; }
else if(temp.isAfter(end)){ return true; }
else{x
events.push({
id: $(this).attr('id'),
title: $(this).attr('artist'),
start: $(this).attr('dato'),
allDay: false
});
}
}
);
});
var ektearray = $.makeArray(events);
callback(events);
}
});
}
});
});
When I output events to the console I get an array of objects, which seem to be working as expected. The objects are in the form:
allDay:false
id:"66"
start:"2016-11-04"
title:"Galantis"
__proto__:Object
It seems like I am either messing up the callback, or that my events are missing something, but I can't seem to figure out what
If I understand correctly, you want to execute the function(doc) upon success of the ajax call. If so, your syntax seems no to be properly written.
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.success(function() {
alert( "success" );
});

select day and special date load by ajax to set in gldatepicker

I am using gldatepicker.I want to load some settings from database by ajax for gldatepicker such as day of week,special date etc.Now i have following js code for this:
$(document).ready(function () {
loadAllSettings();
});
var loadAllSettings = function () {
startDate = '';
endDate = '';
selectDay = '';
offdays = '';
$.ajax({
url: "bs_client_function.php",
type: "post",
dataType: "json",
data: {
action: 'getDateRange'
},
success: function (html) {
// alert(html.start);
startDate = Date.parse(html.start);
endDate = Date.parse(html.end);
}
});
$.ajax({
url: "bs_client_function.php",
type: "post",
dataType: "json",
data: {
action: 'getOffdays'
},
success: function (html) {
i = 0;
offdays = '[';
while (i < html.length) {
offdays = offdays + {
date: new Date(html[i]),
repeatYear: false,
cssClass: 'noday'
};
i = i + 1;
}
offdays = offdays + ']';
}
});
$.ajax({
url: "bs_client_function.php",
type: "post",
data: {
action: 'getDays'
},
success: function (html) {
var data = $.parseJSON(html);
// alert("[" + data + "]");
selectDay = '[' + data + ']';
// alert(selectDay);
showCalender(startDate, endDate, selectDay, offdays);
}
});
alert(selectDay);
console.log('selectDay' + selectDay);
};
I have checked all data is correctlly formated as gldatepicker recommanded.In my show calender
function:
var showCalender = function (startDate, endDate, selectDay, offdays) {
var dd = $('#mydate').glDatePicker({
showAlways: true,
allowMonthSelect: true,
allowYearSelect: false,
prevArrow: '\u25c4',
nextArrow: '\u25ba',
cssName: 'darkneon',
selectableDOW: selectDay,
dowOffset: 0,
selectedDate: new Date(),
selectableDateRange: [{
from: new Date(startDate),
to: new Date(endDate)
}, ],
specialDates: offdays
});
};
Now only stardate and enddate rightly working.selectDay,offdays are not working. i print selectDay in the console i got this: [1,2,3] but it not woking.What i am missing or what should be right way to do it.
Thanks in advance...
The problem is how you are getting your data for fill the glDatePicker.
You have 3 ajax calls, these calls are by default asynchronous, you execute your showCalender function in the last success function, but you have no sureness that the preceding calls are completed.
You can make your ajax calls synchronous by setting the async parameter to false see the jQuery docs:
async (default: true) Type: Boolean By default, all requests are sent
asynchronously (i.e. this is set to true by default). If you need
synchronous requests, set this option to false. Cross-domain requests
and dataType: "jsonp" requests do not support synchronous operation.
Note that synchronous requests may temporarily lock the browser,
disabling any actions while the request is active. As of jQuery 1.8,
the use of async: false with jqXHR ($.Deferred) is deprecated; you
must use the success/error/complete callback options instead of the
corresponding methods of the jqXHR object such as jqXHR.done() or the
deprecated jqXHR.success().
or you can chain them in every success callbacks, but your code will be difficult to mantain or you can use this plugin to manager multiple ajax calls http://docs.jquery.com/AjaxQueue
It works well with local data, see: http://jsfiddle.net/IrvinDominin/V59E7/
Pay attention only at the object that specialDates option needs:
specialDates: [{
date: new Date(0, 8, 5),
data: {
message: 'Happy Birthday!'
},
repeatYear: true,
cssClass: 'special-bday'
}, {
date: new Date(2013, 0, 8),
data: {
message: 'Meeting every day 8 of the month'
},
repeatMonth: true
}]

Categories

Resources