Send Current Calendar events back to server when fetching more events - javascript

as you move to other months and FullCalendar reaches back out to the server to get more events is there a way to send an array of the current events it has rendered?
this is my poor attempt but doesn't seem to work...
document.addEventListener('DOMContentLoaded', function() {
var cursession = []
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
themeSystem: 'bootstrap',
initialView: 'dayGridMonth',
events:
{
url: '/cal_data',
method: 'GET',
extraParams: {
cur_set: JSON.stringify(cursession)
},
failure: function() {
alert('there was an error while fetching events!');
},
success: function(data) {
cursession = []
cursession.push(data)
console.log(cursession)
},
}
});
calendar.render();
});

Related

Calendar::gotoDate method recalls the ajax request defined in the events

I'm using fullCalendar v5 and I configured it to bind the events using an AJAX call.
Let's assume we are in Jan month 2022, if the AJAX call (http://blahblah.com//ReportDates) will return the JSON data with some date values.
Let's say the JSON data has 2021-08-01. Now when I try to change the calendar to go to Aug 1st 2021 date using the in-built method, the AJAX call (http://blahblah.com//ReportDates) will happen once again.
How can I prevent the second call ?
function calendarLoad(ReportID, ReportDate, isInitialLoad) {
try {
var date = new Date();
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
var calendarEl = document.getElementById('calendar');
if (calendarEl != null) {
calendar = new FullCalendar.Calendar(calendarEl, {
initialView: 'dayGridMonth',
validRange: function() {
return {
start: '2016-01-01', //setting the start date to Jan 1st
end: lastDay // setting the end date based on the current date
};
},
headerToolbar: {
left: 'prev',
center: 'title',
right: 'next'
},
events: function(fetchInfo, successCallback, failureCallback) {
var dt;
if (ReportDate == '') {
dt = fetchInfo.startStr.split('T')[0];
} else {
dt = ReportDate;
}
var events = [];
$.ajax({
url: "http://blahblah.com//ReportDates",
type: 'GET',
dataType: 'JSON',
data: {
reportID: ReportID,
startDate: isInitialLoad == true ? '' : dt
},
success: function(response) {
$.map(response, function(r) {
events.push({
id: r.title,
title: 'Available',
start: r.Rpt_Date,
allDay: true,
url: 'http://blahblah.com/Index/?reportID=' + btoa(ReportID) + '&reportDate=' + btoa(r.Rpt_Date),
});
});
successCallback(events);
if (response.length > 0) {
// assigning the latest report date as initial date for calendar, this date is fetched from the ajax response
// This method is making the ajax call once again, I just need to navigate to JSON data date and don't make the
// ajax call once again. Rest all clicks on the calendar should work as usual after the initial load.
calendar.gotoDate(response[0].Rpt_Date);
} else {
calendar.gotoDate(dt);
}
},
error: function(xhr) {
alert('Error while loading the calendar!!!');
}
});
},
eventClick: function(event) {
if (event.event.url) {
event.jsEvent.preventDefault();
window.open(event.event.url, 'RHS',
'toolbar=0,scrollbars=1,location=No,statusbar=0,menubar=1,resizable=1,width=1050,height=590,left=50,top=50');
}
}
});
}
calendar.render();
} catch (e) {
alert(e);
}
}

Events not displaying after fetching from database using Ajax on Fullcalendar V5

I am trying to fetch events from database using Ajax and then display it on FullCalendar Scheduler v5.6.0, I can see that events are returned from database but not rendering.
Here what i have tried so far.
document.addEventListener("DOMContentLoaded", function () {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
initialView: 'dayGridMonth',
headerToolbar: {
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay'
},
events: function (fetchInfo, successCallback, failureCallback) {
jQuery.ajax({
url: "/getrecords",
type: "GET",
success: function (data) {
var events = [];
for (var i = 0; i < data.event.length; i++) {
console.log(data.event[i].title); // It shows all event titles perfectly
events.push({
title: data.event[i].title,
start: data.event[i].from_data,
end: data.event[i].to_date,
});
}
console.log(events) // Here i have list of all events
successCallback(events);
},
});
},
});
calendar.render();
});
If i put static events in events objects it works fine,but not rendering while called from database using Ajax. Any help would be highly appreciated.
Below is the console output.
I achieved this by using this code on my project.
var calendar = new FullCalendar.Calendar(calendarEl, {
initialView: 'dayGridMonth',
headerToolbar: {
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay'
},
events: {
url: encodeURI('/getrecords'),
type: 'GET',
color: 'red', // a non-ajax option
textColor: 'white' // a non-ajax option
}
}

How to call events method after new event source in FullCalendar.js?

I am trying to create a client side filter for events, I have gone with the same approach of addEventSource. I use the events method to conditionally render the events. I just wanna know how to call the events method or even redefine it?
This is the initial code I am using to render the the calendar
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
displayEventTime: false,
navLinks: true, // can click day/week names to navigate views
editable: true,
eventLimit: true, // allow "more" link when too many events
events: (start, end, timezone, callback) => {
$.ajax({
url: 'get-events',
dataType: 'json',
data: {
// our hypothetical feed requires UNIX timestamps
start: start.unix(),
end: end.unix()
},
success: function (res) {
console.log(res)
var events = [];
res.map((value, index) => {
if (value.cadence != null) {
$("#allDropdown").append(`<a id="file-${value.dq_datafile_id}" onclick="selectThis(this)" href="#about">${value.data_file_name}</a>`)
}
if (value.cadence == "WEEKLY") {
if (value.dqfeed__file_status == "RECEIVED") {
const data_file_name = value.data_file_name;
let repeatDay = dow_handler.hasOwnProperty(data_file_name) ? dow_handler[data_file_name] : undefined
events.push({
title: `${value.data_file_name}`,
start: '2020-04-13',
dow: [repeatDay, 1],
color: '#00ff00'
});
}
});
});
});
This is the code I am using to fetch new events or filtered events
const applyCalendarFilter = () => {
var filter = {
type: 'get',
url: 'filter-events',
}
$("#calendar").fullCalendar('addEventSource', filter);
}
The error I get is Uncaught TypeError: Cannot read property 'hasTime' of undefined because the JSON returned doesn't have a start_date or end_date
So I found removeEvents that will clear all the events from the calendar and renderEvents that takes an option argument events and this will render the rest of the events.
So here's the code that did this.
const applyCalendarFilter = () => {
var filter = {
type: 'get',
url: 'filter-events',
}
$("#calendar").fullCalendar('removeEvents');
$.ajax({
url: 'filter-events',
type: 'get',
success: (res) => {
let events = [];
res.map((value, index) => {
if (value.cadence == "WEEKLY"){
events.push({
'title': value.title,
'start_date': value.start_date,
'end_date': value.end_date
}
})
$("#calendar").fullCalendar('renderEvents', events);
}, error: (res) => {
alert('cant get the data');
}
)};

How can I refresh fullcalendar after insert a row in mysql without refresh the page?

my problem is that I do an ajax petition to insert a event to mysql, so if everything is ok I wanted to refresh (refetch events) fullcalendar to see the new insert without refresh page. Besides, I am using TimeGrid View and version 4 of the plugin.
I tested:
calendar.refetch();
calendar.refetchEvents();
$('calendar').fullcalendar('rerenderEvents');
$('calendar').fullcalendar('refetchEvents');
but that does not work, at least in v4.
Calendar Code:
var calendar;
/* Calendario JS */
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
calendar = new FullCalendar.Calendar(calendarEl, {
plugins: [ 'dayGrid', 'timeGrid', 'bootstrap' ],
defaultView: 'timeGridWeek',
themeSystem: 'bootstrap',
locale: 'es',
minTime: "07:00:00",
maxTime: "23:00:00",
header: {
left: 'title', //today, prev, next
center: 'BtnAñadirReserva',
right: 'today, prev,next' //month, basicWeek, basicDay, gendaWeek, agendaDay
},
customButtons: {
BtnAñadirReserva: {
text: "Añadir Reserva",
bootstrapFontAwesome: "fa-calendar-plus Añadir Reserva",
click: function(){
showNoti();
}
}
},
events: {
url: url_controller,
method: 'post',
extraParams: {
accio: "getReservas"
},
failure: function() {
alert('Hubo un error recorriendo las reservas!');
},
color: 'blue', // a non-ajax option
textColor: 'white' // a non-ajax option
},
eventClick: function(calEvent, jsEvent, view) {
getInfoByID(calEvent.event.id);
}
});
calendar.render();
});
$.ajax({
url: url_controller,
type: 'post',
data: {
accio: "insertReserva",
params: json
},
beforeSend: function () {},
success: function(result){
result = JSON.parse(result);
console.log(result);
if(status == true){
$('#calendar').fullCalendar('rerenderEvents');
//calendar.refetch();
//calendar.refetchEvents();
//$('calendar').fullcalendar('rerenderEvents');
//$('calendar').fullcalendar('refetchEvents');
} else {
/* Error sql php */
}
},
error:function (xhr, ajaxOptions, thrownError) {
/* Error ajax petition */
}
});
No errors showed in console/network if I use .fullcalendar but with .refetch it says that it does not a function.
Is not a php problem because I can insert properly and if I refresh page I can see the new event that I added.

Fullcalendar - can't get events to show asp.net

I'm trying to implement fullcalender but I can't get the exemple data to show. I have been following this guide.
I get no errors but the events doesn't show in the calendar. I have tried different solutions but I can't get it to work, also my experience with json is very limited and i would appreciate some help.
public class CalendarController : BaseController
{
public ActionResult ShowCalendar()
{
return View();
}
public ActionResult GetMeetings(double start, double end)
{
using (var db = new ApplicationDbContext())
{
var fromDate = ConvertFromUnixTimestamp(start);
var toDate = ConvertFromUnixTimestamp(end);
var eventList = GetEvents();
var rows = eventList.ToArray();
return Json(rows, JsonRequestBehavior.AllowGet);
}
}
private static DateTime ConvertFromUnixTimestamp(double timestamp)
{
var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
return origin.AddSeconds(timestamp);
}
private List<Events> GetEvents()
{
List<Events> eventList = new List<Events>();
Events newEvent = new Events
{
id = "1",
title = "Event 1",
start = DateTime.Now.AddDays(1).ToString("s"),
end = DateTime.Now.AddDays(1).ToString("s"),
allDay = false
};
eventList.Add(newEvent);
newEvent = new Events
{
id = "1",
title = "Event 3",
start = DateTime.Now.AddDays(2).ToString("s"),
end = DateTime.Now.AddDays(3).ToString("s"),
allDay = false
};
eventList.Add(newEvent);
return eventList;
}
<head>
#section scripts{
<link rel='stylesheet' href='fullcalendar/fullcalendar.css' />
<script src='lib/jquery.min.js'></script>
<script src='lib/moment.min.js'></script>
<script src='fullcalendar/fullcalendar.js'></script>
<script type="text/javascript">
$(document).ready(function () {
$('#calendar').fullCalendar({
theme: true,
header: {
left: 'prev, next, today',
center: 'title',
right: 'month, agendaWeek, agendaDay'
},
buttonText: {
prev: '<',
next: '>'
},
defaultView: 'month',
editable: false,
weekMode: 'liquid',
//allDaySlot: false,
selectTable: true,
//slotMinutes: 15,
events: function (start, end, timezone, callback) {
$.ajax({
url: "/calendar/getmeetings/",
type: 'GET',
dataType: 'json',
success: function (start, end, timezone, callback) {
alert('success');
},
error: function (start, end, timezone, callback) {
alert('there was an error while fetching events!');
},
data: {
// our hypothetical feed requires UNIX timestamps
start: start.unix(),
end: end.unix()
}
});
}
});
});
</script>
}
</head>
<br />
<div class="jumbotron">
<h1>Event Calendar</h1>
<div id="calendar"></div>
</div>
You are not following the tutorial particularly closely, I note, and are using a different methodology to fetch the events.
Within that, you simply forgot to pass the event list back to fullCalendar. You need to execute the callback function which fullCalendar provided to you, and supply your events to it.
Your definition of "success" and "error"'s callback parameters are nonsense, btw - you need to check the jQuery $.ajax documentation (http://api.jquery.com/jquery.ajax/) to see what is provided:
success: function (response) { //response will contain the JSON data from the server
callback(response); //pass the data to fullCalendar. You can pass "response" directly, assuming the response directly contains a JSON array of events
},
error: function(jqXHR) {
alert(jqXHR.responseText);
}
See https://fullcalendar.io/docs/event_data/events_function/ for more details.
You are not passing the events in a right way try passing the events my way its simple.If in case u still didn't get the calendar u need to check the console for some exception. Before passing the events u need the push the data to events.
event_array.push({
userid: v.UserId,
start: moment(v.LoginTime),
//end: moment(v.LogoutTime)
//start: moment(v.start),
end: v.LogoutTime != null ? moment(v.LogoutTime) : null
//color: v.themecolor,
//allday: v.isfullday
});
and then u need to call that in calender id for example
function GenerateCalender(event_array) {
debugger;
//$('#calender').fullCalendar('destroy');
$('#calender').fullCalendar({
events: event_array
});
}
This is my full code-
var event_array = [];
var event_array = [];
var selectedEvent = null;
FetchEventAndRenderCalendar();
function FetchEventAndRenderCalendar() {
events = [];
$.ajax({
url: "/Home/GetEvents",
data: "",
type: "GET",
dataType: "json",
async: false,
cache: false,
success: function (data) {
alert("success");
$.each(data, function (i, v) {
event_array.push({
userid: v.UserId,
start: moment(v.LoginTime),
//end: moment(v.LogoutTime)
//start: moment(v.start),
end: v.LogoutTime != null ? moment(v.LogoutTime) : null
//color: v.themecolor,
//allday: v.isfullday
});
})
GenerateCalender(event_array);
},
error: function (error) {
alert('failed');
}
})
}
function GenerateCalender(event_array) {
debugger;
//$('#calender').fullCalendar('destroy');
$('#calender').fullCalendar({
events: event_array
});
}

Categories