PHP Event Calendar – Add Events to Calendar using jQuery and Ajax

PHP Event Calendar is a user-friendly way to display events dynamically from the database. Not only list the events, but you can also provide an option to add events to the calendar for a specific date. Based on the selected date, the event will be added to the database and list on the calendar dynamically. In the previous PHP event calendar tutorial, you learned how to create an event calendar using jQuery, Ajax, and PHP. In this tutorial, we will enhance the functionality of the PHP event calendar script to show you how to add events to the calendar and display events from the MySQL database using jQuery and Ajax.

The following functionality will be implemented to build an event calendar and add events to calendar using PHP and MySQL.

  • Fetch events from the MySQL database.
  • Display events in the date cell of the large calendar.
  • Navigate between the days/months/years and see the events.
  • Add event to calendar date using jQuery and Ajax.

Since this script is an enhancement of the PHP event calendar script, we will focus mainly on the add event functionality using jQuery, Ajax, PHP & MySQL. Before you begin, see the PHP event calendar tutorial first, it will help to understand our PHP event calendar script.

Before getting started, take a look at the file structure of the Add Event to PHP Calendar script.

php_event_calendar_add/
├── index.php
├── functions.php
├── dbConfig.php
├── js/
│   ├── jquery.min.js
│   └── sweetalert.min.js
└── css/
    └── style.css

Create Database Table

A table is required to store the event information in the database. The following SQL creates an events table with some basic fields in the MySQL database.

CREATE TABLE `events` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `date` date NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Database Configuration (dbConfig.php)

The MySQLi extension is used to connect the database using PHP and MySQL. Specify the database host ($dbHost), username ($dbUsername), password ($dbPassword), and name ($dbName) as per your database credentials.

<?php 
// Database configuration
$dbHost     "localhost";
$dbUsername "root";
$dbPassword "root";
$dbName     "codexworld";

// Create database connection
$db = new mysqli($dbHost$dbUsername$dbPassword$dbName);

// Check connection
if ($db->connect_error) {
    die(
"Connection failed: " $db->connect_error);
}

Helper Functions to Build Calendar and Add Event (functions.php)

The functions.php file holds all the functions that are used to generate a calendar and add events with PHP and MySQL.

  • getCalender()
    • Generate calendar based on the specific month and year.
    • Fetch events from the database and add the events to the date cell of the calendar.
  • getMonthList() – Create months option list for the select box which is used for months dropdown.
  • getYearList() – Create years option list for the select box which is used for years dropdown.
  • getEvents() – Fetch events by date from the database and returns the events list as HTML format.
  • addEvent() – Insert event in the database.
<?php 
// Include the database config file
require_once 'dbConfig.php';

/*
 * Load function based on the Ajax request
 */
if(isset($_POST['func']) && !empty($_POST['func'])){
    switch(
$_POST['func']){
        case 
'getCalender':
            
getCalender($_POST['year'],$_POST['month']);
            break;
        case 
'getEvents':
            
getEvents($_POST['date']);
            break;
        case 
'addEvent':
            
addEvent($_POST);
            break;
        default:
            break;
    }
}

/*
 * Generate event calendar in HTML format
 */
function getCalender($year ''$month ''){
    
$dateYear = ($year != '')?$year:date("Y");
    
$dateMonth = ($month != '')?$month:date("m");
    
$date $dateYear.'-'.$dateMonth.'-01';
    
$currentMonthFirstDay date("N",strtotime($date));
    
$totalDaysOfMonth cal_days_in_month(CAL_GREGORIAN,$dateMonth,$dateYear);
    
$totalDaysOfMonthDisplay = ($currentMonthFirstDay == 1)?($totalDaysOfMonth):($totalDaysOfMonth + ($currentMonthFirstDay 1));
    
$boxDisplay = ($totalDaysOfMonthDisplay <= 35)?35:42;
    
    
$prevMonth date("m"strtotime('-1 month'strtotime($date)));
    
$prevYear date("Y"strtotime('-1 month'strtotime($date)));
    
$totalDaysOfMonth_Prev cal_days_in_month(CAL_GREGORIAN$prevMonth$prevYear);
?>
    <main class="calendar-contain">
        <section class="title-bar">
            <a href="javascript:void(0);" class="title-bar__prev" onclick="getCalendar('calendar_div','<?php echo date("Y",strtotime($date.' - 1 Month')); ?>','<?php echo date("m",strtotime($date.' - 1 Month')); ?>');"></a>
            <div class="title-bar__month">
                <select class="month-dropdown">
                    <?php echo getMonthList($dateMonth); ?>
                </select>
            </div>
            <div class="title-bar__year">
                <select class="year-dropdown">
                    <?php echo getYearList($dateYear); ?>
                </select>
            </div>
            <a href="javascript:void(0);" class="title-bar__next" onclick="getCalendar('calendar_div','<?php echo date("Y",strtotime($date.' + 1 Month')); ?>','<?php echo date("m",strtotime($date.' + 1 Month')); ?>');"></a>
        </section>
        
        <aside class="calendar__sidebar">
            <div id="event_list">
                <?php echo getEvents(); ?>
            </div>
            <a href="javascript:void(0);" class="add-event-btn">+add event</a>
            <div id="event_add_frm" style="display:none;">
                <form id="eventAddFrm" action="#">
                    <div class="form-group">
                        <label>Event Title:</label>
                        <input type="text" class="form-control" name="event_title" id="event_title" required>
                    </div>
                    <div class="form-group">
                        <label>Date:</label>
                        <input type="text" class="form-control" name="event_date" id="event_date" value="<?php echo date("Y-m-d"); ?>" readonly>
                    </div>
                    <input type="submit" name="event_submit" class="btn btn-default" value="Submit">
                </form>
            </div>
        </aside>
        
        <section class="calendar__days">
            <section class="calendar__top-bar">
                <span class="top-bar__days">Mon</span>
                <span class="top-bar__days">Tue</span>
                <span class="top-bar__days">Wed</span>
                <span class="top-bar__days">Thu</span>
                <span class="top-bar__days">Fri</span>
                <span class="top-bar__days">Sat</span>
                <span class="top-bar__days">Sun</span>
            </section>
            
            <?php 
                $dayCount 
1;
                
$eventNum 0;
                
                echo 
'<section class="calendar__week">';
                for(
$cb=1;$cb<=$boxDisplay;$cb++){
                    if((
$cb >= $currentMonthFirstDay || $currentMonthFirstDay == 1) && $cb <= ($totalDaysOfMonthDisplay)){
                        
// Current date
                        
$currentDate $dateYear.'-'.$dateMonth.'-'.$dayCount;
                        
                        
// Get number of events based on the current date
                        
global $db;
                        
$result $db->query("SELECT title FROM events WHERE date = '".$currentDate."' AND status = 1");
                        
$eventNum $result->num_rows;
                        
                        
// Define date cell color
                        
if(strtotime($currentDate) == strtotime(date("Y-m-d"))){
                            echo 
'
                                <div class="calendar__day today" onclick="getEvents(\''
.$currentDate.'\');">
                                    <span class="calendar__date">'
.$dayCount.'</span>
                                    <span class="calendar__task calendar__task--today">'
.$eventNum.' Events</span>
                                </div>
                            '
;
                        }elseif(
$eventNum 0){
                            echo 
'
                                <div class="calendar__day event" onclick="getEvents(\''
.$currentDate.'\');">
                                    <span class="calendar__date">'
.$dayCount.'</span>
                                    <span class="calendar__task">'
.$eventNum.' Events</span>
                                </div>
                            '
;
                        }else{
                            echo 
'
                                <div class="calendar__day no-event" onclick="getEvents(\''
.$currentDate.'\');">
                                    <span class="calendar__date">'
.$dayCount.'</span>
                                    <span class="calendar__task">'
.$eventNum.' Events</span>
                                </div>
                            '
;
                        }
                        
$dayCount++;
                    }else{
                        if(
$cb $currentMonthFirstDay){
                            
$inactiveCalendarDay = ((($totalDaysOfMonth_Prev-$currentMonthFirstDay)+1)+$cb);
                            
$inactiveLabel 'expired';
                        }else{
                            
$inactiveCalendarDay = ($cb-$totalDaysOfMonthDisplay);
                            
$inactiveLabel 'upcoming';
                        }
                        echo 
'
                            <div class="calendar__day inactive">
                                <span class="calendar__date">'
.$inactiveCalendarDay.'</span>
                                <span class="calendar__task">'
.$inactiveLabel.'</span>
                            </div>
                        '
;
                    }
                    echo (
$cb%== && $cb != $boxDisplay)?'</section><section class="calendar__week">':'';
                }
                echo 
'</section>';
            
?>
        </section>
    </main>

    <script>
        function getCalendar(target_div, year, month){
            $.ajax({
                type:'POST',
                url:'functions.php',
                data:'func=getCalender&year='+year+'&month='+month,
                success:function(html){
                    $('#'+target_div).html(html);
                }
            });
        }
        
        function getEvents(date){
            $.ajax({
                type:'POST',
                url:'functions.php',
                data:'func=getEvents&date='+date,
                success:function(html){
                    $('#event_list').html(html);
                }
            });
            
            // Add date to event form
            $('#event_date').val(date);
        }
        
        function getCalendarEvents(target_div, year, month, date){
            $.ajax({
                type:'POST',
                url:'functions.php',
                data:'func=getCalender&year='+year+'&month='+month,
                success:function(html){
                    $('#'+target_div).html(html);
                    getEvents(date);
                }
            });
        }
        
        $(document).ready(function(){
            $('.month-dropdown').on('change',function(){
                getCalendar('calendar_div', $('.year-dropdown').val(), $('.month-dropdown').val());
            });
            $('.year-dropdown').on('change',function(){
                getCalendar('calendar_div', $('.year-dropdown').val(), $('.month-dropdown').val());
            });
            
            $('.add-event-btn').on('click',function(){
                $('#event_add_frm').slideToggle();
            });
            
            $('#eventAddFrm').submit(function(event){
                event.preventDefault();
                $(':input[type="submit"]').prop('disabled', true);
                $('#event_add_frm').css('opacity', '0.5');
                $.ajax({
                    type:'POST',
                    url:'functions.php',
                    data:$('#eventAddFrm').serialize()+'&func=addEvent',
                    success:function(status){
                        if(status == 1){
                            //$('#eventAddFrm')[0].reset();
                            $('#event_title').val('');
                            swal("Success!", "Event added successfully.", "success");
                        }else{
                            swal("Failed!", "Something went wrong, please try again.", "error");
                        }
                        $(':input[type="submit"]').prop('disabled', false);
                        $('#event_add_frm').css('opacity', '');
                        
                        var date = $('#event_date').val();
                        var dateSplit = date.split("-");
                        getCalendarEvents('calendar_div', dateSplit[0], dateSplit[1], date);
                    }
                });
            });
        });
    </script>
<?php
}

/*
 * Generate months options list for select box
 */
function getMonthList($selected ''){
    
$options '';
    for(
$i=1;$i<=12;$i++)
    {
        
$value = ($i 10)?'0'.$i:$i;
        
$selectedOpt = ($value == $selected)?'selected':'';
        
$options .= '<option value="'.$value.'" '.$selectedOpt.' >'.date("F"mktime(000$i+100)).'</option>';
    }
    return 
$options;
}

/*
 * Generate years options list for select box
 */
function getYearList($selected ''){
    
$yearInit = !empty($selected)?$selected:date("Y");
    
$yearPrev = ($yearInit 5);
    
$yearNext = ($yearInit 5);
    
$options '';
    for(
$i=$yearPrev;$i<=$yearNext;$i++){
        
$selectedOpt = ($i == $selected)?'selected':'';
        
$options .= '<option value="'.$i.'" '.$selectedOpt.' >'.$i.'</option>';
    }
    return 
$options;
}

/*
 * Generate events list in HTML format
 */
function getEvents($date ''){
    
$date $date?$date:date("Y-m-d");
    
    
$eventListHTML '<h2 class="sidebar__heading">'.date("l"strtotime($date)).'<br>'.date("F d"strtotime($date)).'</h2>';
    
    
// Fetch events based on the specific date
    
global $db;
    
$result $db->query("SELECT title FROM events WHERE date = '".$date."' AND status = 1");
    if(
$result->num_rows 0){
        
$eventListHTML .= '<ul class="sidebar__list">';
        
$eventListHTML .= '<li class="sidebar__list-item sidebar__list-item--complete">Events</li>';
        
$i=0;
        while(
$row $result->fetch_assoc()){ $i++;
            
$eventListHTML .= '<li class="sidebar__list-item"><span class="list-item__time">'.$i.'.</span>'.$row['title'].'</li>';
        }
        
$eventListHTML .= '</ul>';
    }
    echo 
$eventListHTML;
}

/*
 * Insert events in the database
 */
function addEvent($postData){
    
$status 0;
    if(!empty(
$postData['event_title']) && !empty($postData['event_date'])){
        global 
$db;
        
$event_title $db->real_escape_string($postData['event_title']);
        
$insert $db->query("INSERT INTO events (title, date) VALUES ('".$event_title."', '".$postData['event_date']."')");
        if(
$insert){
            
$status 1;
        }
    }
    
    echo 
$status;
}

Display Calendar and Add Event (index.php)

Call the getCalender() function to embed the event calendar with add option.
Event Calendar:

  • Include the file of the helper functions (functions.php).
  • Use getCalender() function to add calendar in the web page.
  • AJAX request is used to load the respective events on date change, so, include the jQuery library.

Add Event to Calendar:

  • Include SweetAlert JS library (sweetalert.min.js) that helps to display event add status on a popup box.
  • The “add event” button will be added for each calendar date.
  • By clicking the “add event” button, a form will appear with event title and date fields.
  • On submission, the event data will be stored in the MySQL database and the status message will be shown on the popup window.
  • All the events will be listed on the calendar.
<?php 
// Include calendar helper functions
require_once 'functions.php';
?> <!DOCTYPE html> <html lang="en-US"> <head> <title>PHP Event Calendar by CodexWorld</title> <meta charset="utf-8"> <!-- Stylesheet file --> <link rel="stylesheet" href="css/style.css"> <!-- jQuery library --> <script src="js/jquery.min.js"></script> <!-- SweetAlert plugin to display alert --> <script src="js/sweetalert.min.js"></script> </head> <body> <!-- Display event calendar --> <div id="calendar_div"> <?php echo getCalender(); ?> </div> </body> </html>

Conclusion

This example PHP event calendar script helps you to embed a large calendar in the web page and list the events from the database. Also, you can allow the user to add events to the calendar without page refresh using jQuery, Ajax, PHP, and MySQL. The functionality of this event calendar can be enhanced to make it more user-friendly.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

27 Comments

  1. Hideki Said...
  2. Fabricio Said...
  3. Pierre Hungerbühler Said...
  4. Hans Said...
  5. Jan Said...
  6. Mostafa Said...
  7. Farzan Said...
    • CodexWorld Said...
  8. Sara Said...
  9. Creepy Banana Said...
  10. Jacob Said...
  11. Neha Said...
    • CodexWorld Said...
  12. Shobith Said...
  13. POOJA Said...
  14. Dinesh Kumar Said...
  15. Khristian Said...
  16. Nnamdi Wakwe Said...
  17. Wani Said...
  18. Ugyen Said...
  19. Amir Naved Said...
  20. Lennart Said...
  21. Marjul Hossain Said...
  22. Digvijay Said...
  23. Monday Gabriel Said...
  24. Thomas Said...

Leave a reply

keyboard_double_arrow_up