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

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
}
}

Related

Send Current Calendar events back to server when fetching more events

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();
});

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 filtrering events with select

I want to filter events by changing a select option, but I'm not sure how. Some help please(I want to clarify that this is the first time I use Json and FullCalendar)
Example:
Controller cCalendar
public function geteventos(){
$rut_usu = $this->input->post('rut_usu');
$r = $this->mCalendar->geteventos($rut_usu);
echo json_encode($r);
}
Model mCalendar
public function geteventos($rut_usu){
$this->db->select('CONCAT(estudiantes.pnombre," ", estudiantes.apellido_pa," ", estudiantes.apellido_ma,", ",motivos_citas.descripcion_mot) As title ,citas.id_ci id, citas.fecha_ini start, citas.fecha_ter end');
$this->db->from('citas');
$this->db->join('estudiantes', 'citas.rut_estu = estudiantes.rut_estu');
$this->db->join('motivos_citas','citas.id_mot = motivos_citas.id_mot');
$this->db->join('usuarios','citas.rut_usu = usuarios.rut_usu');
$this->db->where('usuarios.rut_usu',$rut_usu);
return $this->db->get()->result();
}
Javascript
$("#rut_usu").change(function(){
rut_usu = $('#rut_usu').val();
$.post('<?php echo base_url();?>cCalendar/geteventos',
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay,listMonth'
},
defaultDate: new Date(),
navLinks: true, // can click day/week names to navigate views
businessHours: true, // display business hours
editable: true,
events: $.parseJSON(data)
});
}));
Your controller and modal is not any changes.
Only changes in js:
Create new javascript function:
function getEvents(rut_usu)
{
$('#calendar').fullCalendar( 'removeEvents');
$.ajax({
type:"GET",
url: "<?=base_url();?>cCalendar/geteventos",
dataType: 'json',
data: {rut_usu:rut_usu },
success: function(data){
$.each(data, function(index, event){
$('#calendar').fullCalendar('renderEvent', event);
});
}
});
}
Call this function into on change dropdown event:
<select id="rut_usu" OnChange="getEvents(this.value);">
-----
</select>
Render Event when change select option.

fullCalendar: Getting data from controller JSON

I am using the fullCalendar library in Visual Studio 2015. I am having trouble populating events from an AJAX command. No events are populating on the calendar. If I pass only one datetime and set allDay = true, it will populate the event. I need it to work with time as well and ave multiple events per day.
JS Code:
$(document).ready(function () {
$(".calendar").fullCalendar
({
header: {
left: 'month,basicWeek,basicDay,today',
center: 'title',
right: 'prev,next'
},
weekends: false,
eventLimit: true,
theme: true,
editable: false,
fixedWeekCount: false,
events: function(start, end, timezone, callback)
{$.ajax
({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Calendar/GetCalendarEvents",
dataType: 'json',
success: function (data)
{
var events = [];
$.each(data, function (index, value) {
events.push({
id: value['id'],
title: value['title'],
date: value['date']
//all data
});
console.log(value)
});
callback(events);
},
error: function (xhr, err) {
alert("ERROR! - readyState: " + xhr.readyState + "<br/>status: " + xhr.status + "<br/>responseText: " + xhr.responseText);
}
});
} });})
Note: The above code was one of may attempts to get it working. I have tried coding it differently before.
Controller Code:
public ActionResult GetCalendarEvents()
{
var events = new List<VMCalendarEvents>();
var db_events = db.PatientVisits.ToList();
foreach(var e in db_events)
{
DateTime visit_start = Convert.ToDateTime(e.VisitStart);
DateTime visit_end = Convert.ToDateTime(e.VisitEnd);
var calEvent = new VMCalendarEvents
{
id = e.PatientVisitID.ToString(),
title = "Placeholder Title" + e.PatientVisitID.ToString(),
date = visit_start.ToShortDateString(),
start = visit_start.ToString(),
end = visit_end.ToString(),
editable = true,
allDay = false
};
events.Add(calEvent);
}
var rows = events.ToArray();
return Json(rows, JsonRequestBehavior.AllowGet);}
Controller Code Output
JS Objects from Controller
EDIT: Problem Solved
So after some investigating I decided to use Razor in MVC to solve the problem. Instead of writing it into a seperate JS file, I put it into a header in the html file. By implementing the code below I was able to get the objects in the date formats of (yyyy-MM-ddTHH:dd & MM/dd/yyyy hh:mm tt):
$(function () {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '2017-06-12',
editable: true,
events: '#Url.Action("GetCalendarEvents", "Calendar")',
});
});
I called the Controller using the URL Action command and return the JSON data as a ActionResult.
Fullcalendar might not like your slashes '/' in your date fields. Try hyphens '-' instead.
The documentation (https://fullcalendar.io/docs/utilities/Moment/) is more detailed about what formats for date/time work.
For reference, here is my fullcalendar code using JSON from AJAX (note that my events do not have an end time, but this was by choice):
{
$.ajax({
url: 'example.json',
dataType: 'json',
success: function(doc) {
var events = [];
$.each(doc, function(index, element) {
events.push({
title: element.title,
start: element.time,
url: element.url,
});
});
callback(events);
}
}) //ajax
}
And the JSON file (example.json):
[
{"time": "2017-06-06 09:00:00", "title": "Get It Done in June ", "url": "http://example.org"},
{"time": "2017-06-07 14:00:00", "title": "Fighting Imposter Syndrome for Dissertating Students ", "url": "http://example.com"},
{"time": "2017-06-14 14:00:00", "title": "Entering into the Academic Conversation", "url": "http://example.biz"}
]

Categories