javascriptphpajaxfullcalendarfullcalendar-3

Trigger an event when next month button clicked on fullcalendar not working


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?


Solution

  • 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:

    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.