0

I am trying to implement a fullcalendar on a website I am building. As my knowledge of javascript is very limited I am strugeling to get the data out of the db and into the javascript.

I am using the codeigniter framework. But I believe this is of no importance to the question.

I tryed to look online for solutions but I believe they changed alot in their last revision of fullcalendar as most if not all examples I find don't work. I am suprised that i even managed to get a blanck calendar to show up.

<div class="container">
    <div class="row">
        <div class="col-md-12">

            <h1>Een kalender</h1>
            <!-- Display Our Calendar -->
            <div id="calendar"></div>

        </div>
    </div>
</div>
<script>

document.addEventListener('DOMContentLoaded', function() {
  var calendarEl = document.getElementById('calendar');
  var date_last_clicked = null;
  var calendar = new FullCalendar.Calendar(calendarEl, {
    plugins: [ 'interaction', 'dayGrid', 'timeGrid' ],
    defaultView: 'dayGridMonth',
    defaultDate: '2019-08-07',
    selectable: true,
    header: {
      left: 'prev,next today',
      center: 'title',
      right: 'dayGridMonth,timeGridWeek,timeGridDay'
    },

    events: function(start, end, timezone, callback) {
        $.ajax({
        url: '<?php echo base_url('calendar/get_events') ?>',
        dataType: 'json',
        data: {
          start: start.unix(),
          end: end.unix()
        },
        success: function(msg) {
            var events = msg.events;
            callback(events);
        }
        });
    }

  });

  calendar.render();
});
</script>
/**
     * Geef de events terug
     */
    public function get_events()
    {
        // Our Start and End Dates
        // $start = $this->input->get("start");
        // $end = $this->input->get("end");

        $start = strtotime('2019-08-01 01:00:00');
        $end = strtotime('2019-08-31 01:00:00');

        $startdt = new DateTime('now'); // setup a local datetime
        $startdt->setTimestamp($start); // Set the date based on timestamp
        $start_format = $startdt->format('Y-m-d H:i:s');

        $enddt = new DateTime('now'); // setup a local datetime
        $enddt->setTimestamp($end); // Set the date based on timestamp
        $end_format = $enddt->format('Y-m-d H:i:s');

        $events = $this->calendar_model->get_events($start_format, $end_format);

        $data_events = array();

        foreach($events->result() as $event) {

            $data_events[] = array(
                "id" => $event->event_id,
                "title" => $event->event_title,
                "description" => $event->event_description,
                "end" => $event->event_end,
                "start" => $event->event_start
            );
        }

// Edited on stackoverflow 
        echo json_encode($data_events);
        exit();
    }
[{"id":"1","title":"Trouw","description":"Familie hoenkeboenke","end":"2019-08-31 00:00:00","start":"2019-08-30 00:00:00"},{"id":"2","title":"Love shoot","description":"Geen flauw idee","end":"2019-08-29 00:00:00","start":"2019-08-29 00:00:00"}]

I would like the events to be shown inside of the calendar.

ADyson
  • 57,178
  • 14
  • 51
  • 63
  • `callback` needs to be called with an array of event objects, according to docs. You are not giving it a plain array - but an object, which has an array under the `events` property. Try with just `echo json_encode($data_events);` instead. – misorude Aug 30 '19 at 12:17
  • Hey i tried it. And it does provide me with a better json. But stil it does not load. It only loads the calendar if i comment out the data:{} in the Javascript. – Pieter-Jan Casteels Aug 30 '19 at 12:34
  • Your server-side code does not seem to be using these start and end parameters yet, so that is probably a problem on the client side. Have you checked the JS console in your browser for errors yet? – misorude Aug 30 '19 at 12:36
  • Yep but as i stated my general knowledge of javascript is nearly none. It also seems to difficult to actualy read it out and follow why it acts like it does. Errors : - start.unix is not a function I also seem unable to get the json read out in my chrome devtools. So i have no idee if it actualy gets loaded – Pieter-Jan Casteels Aug 30 '19 at 13:11
  • That error prevents further script execution, so the actual request won’t be made after that. According to fullcalendar docs, start and end are supposed to be moment.js instances, those have a [unix](https://momentjs.com/docs/#/displaying/unix-timestamp/) method. But I don’t think you can use this the way you are currently trying to - fullcalendar calls the function _“whenever it needs new event data. This is triggered when the user clicks prev/next or switches views.”_ - but without the user doing that, start and end would not be set, so you can not use this for the _initial_ load of data. – misorude Aug 30 '19 at 13:17
  • ok all good and i understand. But how does one instanciate the base then? The events should be loaded when a calendar month is displayed. So it needs to get the data out of the db and then visualize it. – Pieter-Jan Casteels Aug 30 '19 at 13:47

1 Answers1

1

It seems I was working with a combination of old and new code (version 3 and 4 of fullcalendar).

After thinkering and looking mainly at this post:

how to refresh fullcalendar v4 after change events object using ajax

I managed to get it working.

My first mestake was sending threw a json that was badly generated. Here is the updated code if anyone would need.

    /**
     * Geef de events terug
     */
    public function get_events()
    {
        // Our Start and End Dates
        $start = strtotime($this->input->get("start"));
        $end = strtotime($this->input->get("end"));

        // $start = strtotime('2019-08-01 01:00:00');
        // $end = strtotime('2019-08-31 01:00:00');

        $startdt = new DateTime('now'); // setup a local datetime
        $startdt->setTimestamp($start); // Set the date based on timestamp
        $start_format = $startdt->format('Y-m-d H:i:s');

        $enddt = new DateTime('now'); // setup a local datetime
        $enddt->setTimestamp($end); // Set the date based on timestamp
        $end_format = $enddt->format('Y-m-d H:i:s');

        $events = $this->calendar_model->get_events($start_format, $end_format);

        $data_events = array();

        foreach($events->result() as $event) {

            $data_events[] = array(
                "id" => $event->event_id,
                "title" => $event->event_title,
                "start" => $event->event_start,
                "end" => $event->event_end,
                "description" => $event->event_description
            );
        }

        // echo json_encode(array("events" => $data_events));
        echo json_encode($data_events);
        exit();
    }

Then my next mestake was using v3 events: function(start ....)

Here is the new javascript code

document.addEventListener('DOMContentLoaded', function() {
  var calendarEl = document.getElementById('calendar');

  var calendar = new FullCalendar.Calendar(calendarEl, {
    plugins: [ 'interaction', 'dayGrid', 'timeGrid' ],
    defaultView: 'dayGridMonth',
    defaultDate: '2019-08-07',
    selectable: true,
    header: {
      left: 'prev,next today',
      center: 'title',
      right: 'dayGridMonth,timeGridWeek,timeGridDay'
    },
    eventSources: [
      {
        events: function(fetchInfo, successCallback, failureCallback) {
            $.ajax({
              url: '<?php echo base_url('calendar/get_events') ?>',
              dataType: 'json',
              data: {
                "start":fetchInfo.start.toDateString(),
                "end":fetchInfo.end.toDateString()
              },
              success: function(response) {
                successCallback(response);
              }
            });
        },
      }
    ],

  });

  calendar.render();
});