Events Display using PHP AJAX with CLNDR Calendar Plugin

by Vincy. Last modified on July 4th, 2023.

CLNDR Plugin is used to create a calendar interface in a web page. In a previous tutorial, we have seen how to create calendar UI using PHP. The CLNDR is the jQuery plugin to create calendar UI without specifying HTML markup.

The calendar view created by this plugin is mapped with mouse events to go back and forth with the calendar day, month, and year.

In the calendar UI, the dates that have events are highlighted. The events in the database table are retrieved by selecting a date from the calendar UI.

View Demo

An AJAX function will call PHP to fetch events on the selected date. PHP code will respond with JSON data to the AJAX call. In the AJAX success callback, the JSON data response is parsed and displayed to the browser.

This screenshot shows the calendar created by the CLNDR plugin. The highlighted days contain events in the database. On clicking the highlighted days, the events on that day will be listed below the calendar.

events-display-using-php-ajax-with-clndr-calendar-output

Landing Page to Load CLNDR Calendar

In the landing page, a div container plots the output calendar UI created by the CLNDR plugin. This target DIV container’s id is used while initializing the CLNDR plugin.

Also, a div element displays events based on the selected date. Initially, the event container will be empty and dynamically loaded by AJAX on selecting a date. This code shows the HTML containers used to load dynamically created calendar UI and display events.

<html>
<head>
<title>Event Calender</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="clndr.css">
<style>
body {
    font-family: Arial;
}

div#event {
    box-sizing: content-box;
    margin-top: 2px;
    width: 100%;
    text-align: center;
    padding: 10px;
}

.event-row {
    padding: 5px;
}
</style>
</head>
<body>
    <div class="container">
        <div class="cal1"></div>
        <div id="event"></div>
    </div>
    <script
        src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script
        src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
    <script
        src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
    <script src="clndr.js"></script>
    <script src="event.js"></script>
</body>
</html>

Highlighting Event Dates and Displaying Events on Selected Dates using AJAX

This code is used to initialize the CLNDR library function by setting parameters. In this example, the CLNDR options like events and clickEvents are used. The events option will have the available event array.

This will be useful to highlight the calendar dates with events. On the click event of the calendar element, an AJAX call will be sent to the getEventByDate.php by passing the selected date. PHP receives the date param and fetches events from the database.

var calendar = {};
$(document).ready( function() {
    var lotsOfEvents = [];
    
    $.ajax({
        url: 'getEventList.php',
        dataType:'json',
        success: function(data){
        	var datax = [];
        		for(var i = 0;i<data.length;i++) {
        			datax = {"title":data[i].title, "date": data[i].date};
        			lotsOfEvents.push(datax);
        		}
        	    
        	    calendar.clndr = $('.cal1').clndr({
        	        events: lotsOfEvents,
        	        clickEvents: {
        	            click: function (target) {
        	                $.ajax({
        	                    url: 'getEventByDate.php',
        	                    dataType:'json',
        	                    type : 'POST',
        	                    data: {
        	                        eventDate : target['date']['_i']                         
        	                    },
        	                    success: function(json){
        	                    Results(json);
        	                    }
        	                    });
        	                function Results(json){
        	                    $("#event").html("");
        	                		$(".day .day-contents").css("color", "#000");
        	                		$(".calendar-day-"+target['date']['_i']+ " .day-contents").css("color", "#FF0000");
        	                		for(var i = 0;i<json.length;i++) {
        	                			$("#event").append("<div class='event-row'>"+json[i].title+"</div>");
        	                		}
        	                    }
        	                    $("#event").empty();
        	            }
        	        },
        	        
        	        showAdjacentMonths: true,
        	        adjacentDaysChangeMonth: false
        	    });
        }
        });
});

PHP Files to Get Event for CLNDR Calendar

The getEventList.php file fetches all the available events to highlight the event dates. The getEventByDate.php is to fetch events on a particular date. The code for these files is listed below.

getEventList.php

<?php
include 'db.php';
$query = "select * from event";
$result = mysqli_query($conn, $query) or die('Query failed: ' . mysql_error());
$eventResult = array(
    array("title" => "Weekend Party - at Hue residency", "date"=>"2018-06-08"),
    array("title" => "Anniversary Celebration - at Meridian Hall", "date"=>"2018-06-11"),
    array("title" => "Yearly Get Together - at College Campus", "date"=>"2018-06-20"),
    array("title" => "Food Festival", "date"=>"2018-06-31")
);
while ($row = mysqli_fetch_assoc($result)) {
    $eventResult[] = $row;
}
echo json_encode($eventResult);
?>

getEventByDate.php

<?php
   include 'db.php';
    $eventDate = $_POST['eventDate'];
    $query="select * from event where date = '" . $eventDate . "'";
    $result = mysqli_query($conn,$query) or die('Query failed: ' . mysql_error());
    $eventResult = array();
    while ($row = mysqli_fetch_assoc($result)) {
        $eventResult[] = $row;
    }
    echo json_encode($eventResult);           
 ?>

Database event Table Script

The following SQL script is used to deploy the event database in your PHP environment to run this example.

--
-- Table structure for table `event`
--

CREATE TABLE `event` (
  `event_id` int(5) NOT NULL,
  `date` date NOT NULL,
  `title` varchar(256) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `event`
--

INSERT INTO `event` (`event_id`, `date`, `title`) VALUES
(1, '2018-06-08', 'Weekend Party - at Hue residency'),
(2, '2018-06-11', 'Anniversary Celebration - at Meridian Hall'),
(3, '2018-06-20', 'Yearly Get Together - at College Campus'),
(4, '2018-05-31', 'Food Festival');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `event`
--
ALTER TABLE `event`
  ADD PRIMARY KEY (`event_id`),
  ADD UNIQUE KEY `event_id` (`event_id`);

--
-- AUTO_INCREMENT for table `event`
--
ALTER TABLE `event`
  MODIFY `event_id` int(5) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
COMMIT;

View DemoDownload

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “Events Display using PHP AJAX with CLNDR Calendar Plugin”

  • Manish says:

    Thanks Madam, I want to display two column Data on Calendar can you help me Please!

  • Quy says:

    Hi,
    Thanks for useful tutorial…
    But in the demo when I clicked the highlighted days, the events on that day were not listed below the calendar.

  • Andrew says:

    I’m trying to find a code that will highlight a date when a blog article has been posted with a link back to the article. Can this calendar be adapted to do that, and if so what part of the code would need to be changed? Thanks.

    • Vincy says:

      Hi Andrew,

      This code can be adapted and the feature can be incorporated. But it is not something that can be done in one line or simple explanation. Needs to write some amount of code. I will try to update this article or add a new article on this. If you need it urgent, please contact me via email.

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page