Search code examples
javascriptjsonfullcalendarfullcalendar-4

Why does fullcalendar fail to parse JSON?


Summary

I have setup fullcalendar and I'm trying to show data in it using the JSON event source as described in their documentation here.

I keep getting the following failure message Failure parsing JSON.

Things I've tried

This is the JSON which will trigger the failure message [{"title":"Lorem Ipsum","start":"2019-04-01","end":"2019-04-02"},{"title":"The Test","start":"2018-09-01","end":"2018-09-02"}]

I am using fullcalendar version 4.0.2.
I have validated the json my PHP code returns in a linter.
I have added a Content-Type: application/json header to the json response.
I have tried using the eventDataTransform hook to return some sample JSON found in the fullcalendar docs here (see code in edit history)

~~The strange thing is that when I place the above JSON directly in my javascript in the events option it does work.~~ EDIT: As pointed out by Jaromanda X and Quentin this is a javascript array and not JSON.

Code

    var calendar = new FullCalendar.Calendar(calendarEl, {
        plugins: [ 'dayGrid' ],
        defaultView: 'dayGridMonth',
        locale: 'nl',
        events: '/fullcalendar/json.php'
    });

I would expect that my json could be parsed as the response is the same as what I give directly to the events option

Additional info

Contents of the json.php file

<?php
header('Content-Type: application/json');
echo json_encode([
    [
        'title' => 'Lorem Ipsum',
        'start' =>  '2019-04-01',
        'end' =>  '2018-04-02'
    ],
    [
        'title' => 'The Test',
        'start' =>  '2018-09-01',
        'end' =>  '2018-09-02'
    ]
]);exit;

I have tried changing the method to GET which did not help.

I have attached a screenshot of the response I see in the network tab of the inspector JSON response in inspector


Solution

  • I'm afraid my solution probably won't be of much use to anyone else but here it is.

    The error was caused due to the following line of js code in our main js file.

      if($('table').length > 0){
             $('table').wrap('<div class="table-scroll"></div>');
        }
    

    This line messed with the HTML ouput that fullcalender generates which then threw the failure parsing json error.