aniruddh aniruddh - 6 months ago 48
Javascript Question

SyntaxError: missing ; before statement while showing events in full calendar

Im trying to showing dynamically showing events in full calendar in my project. There is a error i didn't understand what the reason behind this ,However when i hard code events array its working fine.

Calendar Jquery Code :

$(document).ready(function() {
$('.fullcalendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
events: [
eventList()
]
});


Ajax Call

function eventList(){
$.ajax({
url :'/calendarMaintenanceData',
type: 'GET',
dataType: 'json',
success:function(data){
$.each(data, function (index, item) {
{
id:item.id,
title:item.machinecode,
start:item.estimated_maintenance_date
}
});
}
});
}


Error :

enter image description here

Answer

eventList needs to put all the events into an array. You can use $.map instead of $.each to do this.

    success:function(data){
        return $.map(data, function (item) {  
            return {                                                                                    
                id:item.id,
                title:item.machinecode,
                start:item.estimated_maintenance_date
            };
        }); 
    }

However, this still won't. The problem is that $.ajax is asynchronous, so the return value of the callback function won't be returned to the fullCalender function. You need to call fullCalendar in the callback function after creating the array.

function eventList(callback){
    $.ajax({
        url :'/calendarMaintenanceData',
        type: 'GET',
        dataType: 'json',
        success:function(data){
            callback($.map(data, function (item) {                                                                                      
                return {
                    id:item.id,
                    title:item.machinecode,
                    start:item.estimated_maintenance_date
                };
            }); 
        }
    });
}

$(document).ready(function() {
    eventList(function(events) {
        $('.fullcalendar').fullCalendar({
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,basicWeek,basicDay'
            },
            events: events
        });
    });
});