I am trying to use an ajax call in the events option of fullcalendar with a json feed, but it's not working. I am working in an asp.net mvc4 application. My ajax call works fine, returns json as expected, but as a test I am just trying to create a local array, called events, add some sample data and pass it to the callback. But for some reason this does not get set in the fullcalendar code, and this does not show on the rendered calendar. I am debugging into the fullcalendar source, but haven't yet figured out why it's not getting set. Any ideas?
$('#calendar').fullCalendar({
theme: false,
timeFormat: '',
height: 'auto',
weekends: true,
events: function (start, end, callback) {
$.ajax({
type:'POST',
url: '#Url.Content("~/Home/GetJson")',
dataType: 'json',
data: {
start: start.toLocaleString("yyyy-mm-dd"),
end: end.toLocaleString("yyyy-mm-dd")
},
error: function (xhr, type, exception) { alert("Error: " + exception); },
success: function (response) {
var events = [];
events.push({
title: "new title",
start: "2014-11-05T13:15:30Z"
});
callback(events);
}
});
}
});
I have confirmed fullcalendar works if I pass in a json string in the events option like this
events:
[{ title: 'Event1', start: '2014-11-05T13:15:30Z' },
{ title: 'Event2', start: '2014-11-06T13:15:30Z' }]
Assuming you are using FullCalendar 2.*, the signature for events as a function is:
function( start, end, timezone, callback ) { }
As long as your event object is valid (you need to have a title and a start), your code should work if you change
events: function (start, end, callback) {
to
events: function (start, end, timezone, callback) {
Related
Getting JSON from CodeBehind with additional None Standard fields using ASP.NET.
Im getting the "standard" title,start,end,color,ClassName correctly when passing "obj" to addEventSource.
The problem is that i would like to use the "Events" and "eventRender" instead of using "addEventSource" to be able to handle the None Standard fields, this doesn't work.
Is it possible to pass object or JSON to "Events"?
I have also tried to use the "docd" (the none parseJSON string) not getting any results displayed in the calendar. Using FullCalendar 3
ex.
events: obj,
eventRender: function(event, element) {
Console.log(info.event.extendedProps.PrjectID)
}
This is request Ajax:
$.ajax({
type: "POST",
url: "Calender.aspx/GetTimeData",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ 'year': year, 'month': month, 'projectID': projectid }),
dataType: "json"
}).done(function (doc) {
var events = [];
docd = doc.d;
obj = $.parseJSON(doc.d);
}
});
ExtraParameters:
ProjectID,UserID,WorkTypeID,Signed
Json:
[{"Signed":1,"ProjectID":39,"WorkTypeid":1,"UserID":97,"id":719627,"start":"2019-01-01T07:00:00","end":"2019-01-01T15:00:00","title":"Test Title ","color":"#607d8b","className":null}]
********************* UPDATE 1 *********************
Edited the code, the ajax request works without any problems when implemented within the fullcalendar environment, BUT the posts will not appear in the calendar, also the "eventRender" is not triggered.
$('#calendar').fullCalendar({
loading: function (bool) {
//LoadEvents();
//alert('events are being rendered'); // Add your script to show loading
},
eventAfterAllRender: function (view) {
//alert('all events are rendered'); // remove your loading
},
navLinks: true,
lazyFetching: false,
height: "auto",
aspectRatio: 2,
weekends: true,
weekNumbers: true,
displayEventEnd: true,
showNonCurrentDates: false,
weekLabel: "V",
allLocales: true,
locale: "sv",
header: false,
//header: {
// //left: 'prev,next today',
// left: '',
// center: '',
// right: 'month,agendaWeek,agendaDay,listMonth'
//},
viewRender: function (element, view) {
var title = view.title;
$("#CalendarHeadTitle").html(title);
//element.find('.fc-title').append("-test-");
},
dayClick: function (date, jsEvent, view) {
$("#sDate, #eDate").val(moment(date).format("YYYY-MM-DD"));
$('.modal').modal('show');
},
eventClick: function (info) {
$('.modal').modal('show');
},
eventDrop: function (event, delta, revertFunc) {
//TODO: Implement - call to move!
if (!confirm("Vill du flytta ")) {
revertFunc();
}
},
editable: true,
events: function (start, end, timezone, callback) {
$.ajax({
type: "POST",
url: "Calender.aspx/GetTimeData",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ 'year': $("#<%=DdlYear.ClientID%>").val(), 'month': $("#<%=DdlMonth.ClientID%>").val(), 'projectID': $("#<%=DdlProjects.ClientID%>").val() }),
dataType: "json"
}).done(function (doc) {
var events = $.parseJSON(doc.d);
console.log(doc.d);
callback(events); //this provided callback function passes the event data back to fullCalendar
});
},
eventRender: function (event, element) {
console.log('event render action');
}
});
I think you are mixing up the syntax and functionality of fullCalendar 3 and fullCalendar 4. They are very different.
Console.log(info.event.extendedProps.PrjectID)
will fail because
a) you haven't defined an info variable in your function parameters (so you should be getting a Console error, although you didn't mention one), and
b) even if you fix that, I strongly suspect (based on the signature you've used for your eventRender function, and the fact you're making extensive use of jQuery) that you're actually using fullCalendar 3, whose event object doesn't have an "extendedProps" property.
If my assumption is correct then I would expect
console.log(event.ProjectID);
to output the required data.
P.S. Your code is shown somewhat out of context, so I'm not sure exactly how you're going about loading the events, but you don't need to have a process where you make an AJAX call outside the calendar environment, and then pass the resulting array to the calendar later. Instead, use one of fullCalendar's built-in features for dealing with dynamic event sources. In your case, the events-as-a-function option is probably the most suitable.
This is the recommended way to connect your data to the calendar.
You can implement it like this:
events: function( start, end, timezone, callback ) {
$.ajax({
type: "POST",
url: "Calender.aspx/GetTimeData",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ 'year': year, 'month': month, 'projectID': projectid }),
dataType: "json"
}).done(function (doc) {
var events = $.parseJSON(doc.d);
callback(events); //this provided callback function passes the event data back to fullCalendar
});
}
FullCalendar will run this code every time it needs new events (e.g. when the calendar loads, and whenever the user changes the calendar view to cover a date range for which it hasn't already fetched events). As you can see, fullCalendar provides you with start and end dates via the callback parameters, which you can pass directly to your server to help it filter the list of events it returns to cover the date range required. Your code currently accepts "month" and "year", so could get those from the start date passed in, but if you are using anything other than "month" views then this won't be flexible enough.
I am using fullcalendar plugin for our users to set their available times. Now everything works fine when reloading the page and when user adds one event, but when they add another event or start selecting, the page almost frozes. I tried all the solutions I found out on Stack but nothing.
I tried calendar.fullCalendar('addEventSource', response.new_events); to add only the new events returned, but lag persist. Tried removing all the eventRender functions, but still the same result. Only thing that seems to work is when I reload the page after each event insert.
IS there any way to decrease the lag while adding new eventSource after select?
These are the parts of my calendar js code
eventSources: [{
url: '/nanny/calendar/availability/all',
type: 'GET',
success: function (response) {
},
error: function (jqXhr, textStatus, errorThrown, data) {
$(".loading-icon").hide();
console.log(jqXhr, textStatus, errorThrown, data);
},
}],
eventRender: function (event, element) {
var delete_icon = '<i style="float: right; cursor: pointer;" class="' + event.icon + '"></i>';
if (event.icon) {
element.find("div.fc-time").append(delete_icon);
}
},
eventAfterRender: function (event, $el, view) {
$(".loading-icon").hide();
var formattedTime = $.fullCalendar.formatRange(event.start, event.end, "HH:mm");
// if event has fc-short class, data-start value will be displayed
// remove fc-short class and update fc-time span text
if ($el.is('.fc-short')) {
$el.find(".fc-time span").text(formattedTime + " - " + event.title);
$el.removeClass('fc-short');
$el.find('.fc-title').remove();
}
},
select: function (start, end) {
//in the past so give error
if (start.isBefore(moment())) {
$('#calendar').fullCalendar('unselect');
return false;
}
//get the event data
eventData = {
start: moment(start).format('YYYY-MM-DD HH:mm:ss'),
end: moment(end).format('YYYY-MM-DD HH:mm:ss')
};
if (eventData) {
if (eventData) {
$.ajax({
type: "POST",
url: "/nanny/calendar/store",
data: eventData,
dataType: "JSON",
success: function (response) {
console.log(response);
swal({
title: "Yay",
text: response.msg,
type: "success",
showCancelButton: false,
confirmButtonColor: "#e36159",
confirmButtonText: "CLose",
closeOnConfirm: false
});
calendar.fullCalendar('addEventSource', response.new_events);
},
error: function (jqXhr, textStatus, errorThrown, data) {
console.log(jqXhr, textStatus, errorThrown, data);
}
});
}
}
},
EDIT
Here's the video.
Lag example
A single event should be added using the renderEvent method. Create the event struct using the appropriate input and pass it to the renderEvent method.
$.ajax({
type: "POST",
url: "/nanny/calendar/store",
data: eventData,
dataType: "JSON",
success: function (response) {
var myEvent =
{
id: response.ID,
title: response.TITLE,
start: eventData.start,
end: eventData.end,
};
$( "#calendar" ).fullCalendar( "renderEvent", myEvent );
}
});
According to the documentation (https://fullcalendar.io/docs/event_data/Event_Object/) the start, end, and title attributes are required. If you are not collecting a title you can hardcode it to something such as "Event".
If you are updating your events in a db and want to allow your users to modify an event (ie. drag and drop, resize, etc.) without refreshing/reloading the calendar you must also provide the id attribute. This can be the unique key assigned to the meeting when stored in the database. You will want to pass this value back in the ajax response. If this functionality is not necessary, then you can ignore the id attribute.
**refetchEvents recall the function CalendarApp.prototype.init and refresh the calendar **
$.ajax({
url: "BASE_URL",
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
"Content-Type": "application/json"
},
type: "POST",
data: JSON.stringify(dataEvent),
dataType: "json",
contentType: "application/json",
success: function(data) {
window.swal({
title: "Checking...",
text: "Please wait",
buttons: false,
timer: 2000
});
$("#calendar").fullCalendar("refetchEvents",dataEvent);
}
});
I am trying to use this great UI "FullCalender" But what I want to do is send an ajax request to update the event data in the database when the user move the event around.
So If a user want to move an event to a different date in the calender then I need to be able to send the request to the database use ajax request.
How can I collect the new information so if the appointment was moved to a new date or a new time how can I obtain the new information so I can pass it along to the server?
More, what method do I use to send the same request if the user changes the time by expanding not by drag/drop event?
$(document).ready(function() {
$('#calendar').fullCalendar({
editable: true,
events: "json-events.php",
timeFormat: 'h:mm{ - h:mm}',
defaultView: 'agendaDay',
eventDrop: function(event, delta, minuteDelta, allDay, revertFunc) {
if (!confirm("Are you sure about this change?")) {
revertFunc();
}
// AJAX call goes here
$.ajax();
},
loading: function(bool) {
if (bool) $('#loading').show();
else $('#loading').hide();
}
});
});
Take a look at the parameters of the function: delta, minuteDelta and allDay. Those tell you how the event was modified in days, minutes and if it was moved to the allday slot. The event itself should hold an identifier so that you can identify it in your database.
I made me a helper function updateEventTimes which is simply called from eventDrop and eventResize with an extra boolean parameter.
The function looks roughly like this:
/*
* Sends a request to modify start/end date of an event to the server
*/
function updateEventTimes(drag, event, dayDelta, minuteDelta, allDay, revertFunc)
{
//console.log(event);
$.ajax({
url: "update.php",
type: "POST",
dataType: "json",
data: ({
id: event.id,
day: dayDelta,
min: minuteDelta,
allday: allDay,
drag: drag
}),
success: function(data, textStatus) {
if (!data)
{
revertFunc();
return;
}
calendar.fullCalendar('updateEvent', event);
},
error: function() {
revertFunc();
}
});
};
Since I found this topic now, I think information below will be helpful in future.
You could use JSON.stringify() method to generate JSON as send date.
But, small workaround need in this case: see Tip on serializing event in fullCalendar with JSON.stringify.
In short, you code should looks like:
/*
* Sends a request to modify start/end date of an event to the server
*/
function updateEventTimes(drag, event, dayDelta, minuteDelta, allDay, revertFunc)
{
delete event.source;
$.post(
"update.php",
event,
function(result) {
if (!result) revertFunc();
}
)
.fail(function() {
revertFunc();
});
};
I am using fullcalendar eventSources to pull json event data from server. I have a variable sheet_id that changes and the selected_sheet_id() function will return the corresponding sheet selected. The problem is that when I call $("#calendar").fullCalendar('refetchEvents') to return events, sheet_id (thus all the events) are always the same. That is fullcalendar does not get refreshed with the current sheet_id before fetching events. How do I trigger the eventSources to "recompile" so that it pulls the correct sheet_id from the function before executing ajax call.
eventSources: [{
url: '/event/get_events',
type: 'GET',
data: {
sheet_id: selected_sheet_id()
},
error: function() {
alert('there was an error while fetching events!');
}
}]
First Try this with async:false for sync call :
eventSources: [
{
url: '/event/get_events',
type: 'GET',
async:false,
data:{
sheet_id: selected_sheet_id()
},
error: function() {
alert('there was an error while fetching events!');
},
},
]
Otherwise made one method which fetch event data in using Ajax call For ex :
var ajaxreturnstring="";
$.ajax({
type: "POST",
url: "/EMR-PHR/getPatientScheduleajax.html",
dataType:"html",
data: "",
async:false,
success: function(data){
ajaxreturnstring=$.trim(data);
var obj = eval("("+txt+")");
return obj;
},
error: function(e){
alert('Error: ' + e);
}
});
}
Is there a good way to have the fullCalendar jquery plugin auto-refresh its events?
I am able to simply call 'refetchEvents' using a timer, but that presents issues if the user is currently dragging an event (throwing javascript errors during the refresh while the event is dragged). Is there a better way?
Good solution... but is not enough:
var calE = {
url: 'calendarEvents.do',
type: 'POST',
data: {
siteId: $("#siteId").val()
},
error: function() {
alert('there was an error while fetching events!');
}
};
function loadCal(){
$('#calendar').fullCalendar({
theme: true,
events: calE,
editable: false,
eventDrop: function(event, delta) {
alert(event.title + ' was moved ' + delta + ' days\n' +
'(should probably update your database)');
},
loading: function(bool) {
if (bool) $('#loading').show();
else $('#loading').hide();
},
viewDisplay: function(viewObj) {}
});
}
function reloadCalendar(){
$('#calendar').fullCalendar('removeEventSource', calEvent );
var source = {
url: 'calendarEvents.do',
type: 'POST',
data: {
siteId: $("#siteId").val()
},
error: function() {
alert('there was an error while fetching events!');
}
};
$('#calendar').fullCalendar('removeEvents');
$('#calendar').fullCalendar('addEventSource', source );
$('#calendar').fullCalendar('rerenderEvents');
calE = source;
}
By using this you'll keep the original algorithm to fetch the data.
you'd just need to keep track of a flag, whether auto-refreshing should happen. it should be true by default, but set to false when dragging or resizing. you can set it based on the eventDragStart, eventDragStop, eventResizeStart, and eventResizeStop.
see http://arshaw.com/fullcalendar/docs/event_ui/ for a list of mouse-related triggers.