I have used AJAX to request data from the database through an API. Here is the function.Since the formatting in the dB is different from the one Full Calendar requires, I have created an Object called schedule that looks the same as an Event Object to store each event item. Then push each object into an array called schedules. (In case anyone ask, reformattingTime() is just changing the string I get from database from HHMM to HH:MM:SS format)
function getCourse(arr){
$.ajax({
type: "GET",
url: '/course',
success: function(req){
for (var i = 0; i < req.length;i++){
var schedule = {daysOfWeek:[]};
schedule.title = req[i].course_name;
schedule.daysOfWeek = req[i].course_day;
schedule.startTime = reformattingTime(req[i].course_starttime);
schedule.endTime = reformattingTime(req[i].course_endtime);
arr.push(schedule);
}
},
error: function(err){
alert('Error:' + err);
}
}
)
}
here's how schedules[0] looks like
Next when I load the page, I add schedules as an event source then render the calendar. However, the events wouldn't appear in the calendar.
<script>
var schedules = [];
$(document).ready(function(){
getCourse(schedules);
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
plugins: ['timeGrid', 'dayGrid', 'interaction', 'list'],
header:{
left: 'timeGridWeek,listMonth'
},
defaultView: 'timeGridWeek',
});
calendar.addEventSource(schedules);
calendar.render();
});
If I hard code the array, the events can be displayed. I have checked that the schedule object from getCourse() is the same as the one I have hard coded.
<script>
var schedules = [{
title: "A1",
startTime: "18:00:00",
endTime: "20:00:00",
daysOfWeek:['1']
}];
$(document).ready(function(){
getCourse(schedules);
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
plugins: ['timeGrid', 'dayGrid', 'interaction', 'list'],
header:{
left: 'timeGridWeek,listMonth'
},
defaultView: 'timeGridWeek',
});
calendar.addEventSource(schedules);
calendar.render();
});