2

I have the following fullcalendar and it is loading current month data. This is loading correctly with all the events.

$(document).ready(function() {
  var d = new Date();
  var defaultMonth = d.getMonth() + 1;
  var defaultYear = d.getFullYear();
  $.ajax({
    type: "POST",
    url: "calendarChangeAjax.php",
    data: {
      selectedMonth: defaultMonth,
      selectedYear: defaultYear
    },
    success: function(mainResult) {
      var mainResults = JSON.parse(mainResult);
      console.log(mainResults);
      populateCalendar(mainResults);
    }
  });
});

function populateCalendar(jArray) {
  var colors = "white";
  var dict = [];
  var details;
  for (i = 0; i < jArray["start"].length; i++) {
    var dates = jArray["start"][i];
    if (jArray["title"][i] != null) {
      details = jArray["title"][i];
      colors = "#E0F8E0";
      dict.push({
        "title": details,
        "start": dates,
        "color": colors
      });
    }
  }
  jArray.length = 0;
  //    var todayDate = new Date();
  $('#calendar').fullCalendar({
    //        defaultDate: todayDate,
    eventLimit: true, // allow "more" link when too many events
    events: dict
  });
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.1.0/fullcalendar.min.css" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.7/semantic.min.css" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.7/semantic.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.1.0/fullcalendar.min.js"></script>

<div class="ui container">
  <div class="ui grid">
    <div class="ui sixteen column">
      <div id="calendar"></div>
    </div>
  </div>
</div>

Following is the codes in the Ajax file calendarChangeAjax.php

$selectedMonth = $_POST['selectedMonth'];
$selectedYear = $_POST['selectedYear'];
$detailsArray = [];
$datesArray = [];
$query = "SELECT * FROM supervisorupdate WHERE MONTH(dateAdded) = '$selectedMonth' AND YEAR(dateAdded) = '$selectedYear' AND status =0";
$queryExecute = mysqli_query($conn, $query);
while ($queryExecuteResults = mysqli_fetch_array($queryExecute)) {
  $oa1 = $queryExecuteResults['oa1'];
  $oa2 = $queryExecuteResults['oa2'];
  $dateAdded = date("Y-m-d", strtotime($queryExecuteResults['dateAdded']));
  $singleDetail = $oa1.$oa2;
  array_push($detailsArray, $singleDetail);
  array_push($datesArray, $dateAdded);
}
$detailsDictionary = ["title" => $detailsArray];
$datesDictionary = ["start" => $datesArray];
$completedDictionary = array_merge($detailsDictionary, $datesDictionary);
echo json_encode($completedDictionary);

I want the fullcalendar to change events when I click on the next month button based on that month. So I added the following codes

$('body').on('click', 'button.fc-next-button', function() {
  var selectedMonth = $('#calendar').fullCalendar('getView').intervalStart.format('MM');
  var selectedYear = $('#calendar').fullCalendar('getView').intervalStart.format('YYYY');
  $.ajax({
    type: "POST",
    url: "calendarChangeAjax.php",
    data: {
      selectedMonth: selectedMonth,
      selectedYear: selectedYear
    },
    success: function(nextResult) {
      var nextResults = JSON.parse(nextResult);
      console.log(nextResults);
      populateCalendar(nextResults);
    }
  });
});

I am getting nextResults correctly from Ajax call.

{title: Array(7), start: Array(7)}

But somehow, events are not showing when I click next button. It always shows only default data when fullcalendar loaded for the first time. Can someone help me on this?

Anu
  • 1,123
  • 2
  • 13
  • 42
  • 1
    1) If you configure Fullcalendar with the URL of your events feed, it will automatically retreive new events when you navigate. You do not need to do anything. [From the docs](https://fullcalendar.io/docs/events-json-feed): "*FullCalendar will visit the URL whenever it needs new event data. This happens when the user clicks prev/next or changes views. FullCalendar will determine the date-range it needs events for and will pass that information along in GET parameters.*". – Don't Panic Dec 09 '21 at 05:52
  • 2) This whole architecture is much more complicated than it needs to be. Fullcalendar will handle all of this. No need for an AJAX call on document ready; no need to `populateCalendar()` when AJAX is done ... Just set up Fullcalendar, tell it you have a JSON feed of events. I'd suggest adding your colours, titles, etc in the PHP which generates the feed. – Don't Panic Dec 09 '21 at 05:53
  • @Don'tPanic Thank you for the comments. I am new to `fullCalendar` and still exploring it. So I still need to check your recommended way – Anu Dec 09 '21 at 05:56
  • If you're new to fullCalendar, don't use the older jQuery-based version, as you have done above, use the latest v5 which is more efficient and has more features. (That doesn't prevent you from using jQuery elsewhere on the same page though of course, if you want to.) – ADyson Dec 09 '21 at 06:42

1 Answers1

2

Update: As pointed out in the comments (thanks @ADyson), your JS is referencing Fullcalendar v3. That's quite old now, v5 is current. My original answer referenced v5 docs, I've updated with v3 links/options as well.

Here's a super simple example. Notes:

  • If you don't specify an initialDate (v5), (or defaultDate in v3) it will default to the current date - so no need to set up the current date.

  • If you configure a JSON feed for events:, Fullcalendar will use GET to request them. If you want to use POST, you can do that, using the eventSources extended format (v5) (or v3). However, convention is that POST is for changing data (eg making a purchase, updating a record), while GET is for reading data. AFAICT you're just loading event data, which should really be a GET. I'd suggest sticking with convention and updating your back end to respond to GET instead of POST.

  • Fullcalendar will automatically make a new request to your event feed when it needs new data, eg when you navigate to a new month. No need to add any code to manually handle that.

JS (v5):

document.addEventListener('DOMContentLoaded', function() {
    var calendarEl = document.getElementById('calendar');
    var calendar = new FullCalendar.Calendar(calendarEl, {
        initialView: 'dayGridMonth',
        dayMaxEventRows: 3, // I think this is the v5 equivalent of eventLimit
        events: 'calendarChangeAjax.php',
    });
    calendar.render();
});

JS (v3):

// Fullcalendar v3 with jQuery
$(document).ready(function() {
    $('#calendar').fullCalendar({
        eventLimit: true, // allow "more" link when too many events
        events: 'calendarChangeAjax.php',
    });
});

I am not sure exactly what your PHP is doing with the 2 merged result sets. But as long as you generate a JSON feed from an array that looks like this, Fullcalendar will handle it:

[
    {
      "title": "Event 1",
      "start": "2019-09-05T09:00:00",
      "end": "2019-09-05T18:00:00",
      "color: "#E0F8E0"
    },
    {
      "title": "Event 2",
      "start": "2019-09-08",
      "end": "2019-09-10",
      "color: "#E0F8E0"
    }
]

The docs describe other properties you can add to your events.

Don't Panic
  • 13,965
  • 5
  • 32
  • 51
  • 1
    1. There are two `events` in your `fullCalendar`. Is this a typo? 2. With this method, how can I pass the selected month and selected date to the php file so that my query can use those to fetch data? – Anu Dec 09 '21 at 06:25
  • Careful...OP is using fullCalendar 3 but the docs links in this answer are for v5. I think OP should just upgrade, since they said they have only just started using fullCalendar, but the links should really answer the question for the version being used in the question. Otherwise, great answer. – ADyson Dec 09 '21 at 06:44
  • 1
    @Anu yes thanks, typo, I wrote this quickly and a bit carelessly. Fixed. RE: passing dates - if you check the links I included to the events docs, you'll see Fullcalendar does this automatically, in the format: `?start=2013-12-01&end=2014-01-12`, where those dates are the start/end of the current view. – Don't Panic Dec 09 '21 at 07:25
  • 1
    @ADyson - thanks, I missed that, wrote this too fast and sloppily. Updated. – Don't Panic Dec 09 '21 at 07:25