Search code examples
javascriptphpjsonfullcalendarfullcalendar-4

How do I use JSON properly to pass Events/EventSources to FullCalendar?


My end goal to pass eventSources via JSON dynamically. Before I even get to producing the JSON content dynamically, I am trying to use the documentation example to pass a simple single event via a JSON URL into my event tag, written manually.

I can see the URL works because I can echo the results in my wordpress website via php, but the JS script i'm passing the JSON URL to just crashes the calendar. I'm really scratching my head on this one.

There's also mention of the prev/next buttons triggering a GET to the JSON with the local timezone dates (say for the range of the currently displayed month). How am I supposed to syntax the json so as to have the event call find the data points range? I'm just really confused about all this.

JSON File: calendar.json


{
    "title" : "something",
    "start" : "2019-04-23"  
}

PHP File: page-calendar.php

<?php
    //Wordpress function for URL to the file location
    $url = get_stylesheet_directory_uri() . '/calendar.json'; 
    $data = file_get_contents($url);
    $content = json_decode($data);

    echo $content->title; // Just to test if the URL works 
    echo $content->start; // This echos just fine

    ?>
<html lang='en'>
      <head>
        <meta charset='utf-8' />
        <script>
          document.addEventListener('DOMContentLoaded', function() {
            var calendarEl = document.getElementById('calendar');

            var calendar = new FullCalendar.Calendar(calendarEl, {
              plugins: [ 'dayGrid' ],

              events: $url;
            });

            calendar.render();
          });
        </script>
      </head>
      <body>
        <div id='calendar'></div>
      </body>
</html>

Solution

  • The JSON needs to be an array of events (even if the array only contains one object). Currently you have a single object, and fullCalendar won't read that.

    Make your calendar.json file look like this:

    [
      {
        "title" : "something",
        "start" : "2019-04-23"  
      }
    ]
    

    You'll also need to change the code a bit so that your PHP $url variable is treated as PHP and rendered, and also so the output is treated as a string by JS, not just injected into the JS as-is:

    events: "<?php echo $url; ?>"