Create PHP Event Calendar With JQuery & AJAX To Manage Events

The PHP event calendar can be very useful element for any web development project. The calendar can be used to manage events by running basic operations through AJAX requests. To achieve this, go through following steps to integrate PHP event calendar in your website.

In this PHP calendar tutorial, the functionalities are divided into following four parts.

  • Database
  • JS
  • CSS
  • CODE

We’ll start with the database.

Begin by login-in into your phpmyadmin. Common URL for login is http://localhost/phpmyadmin

In there, click on database, enter your database name, and press ‘Create’ button.

Select the database created by you and look for import button. Click on it once you find it, here you can see a browse button. Click browse and select ‘event_calendar.sql’ file from your system and import it. You’ll receive an import successful message once done.

Now next, JS and CSS files are required to put into project directory.

We’ll begin by creating php calendar code for required files.

  1. Index.php
  2. Connection.php
  3. Functions.php

First, create a new file and name it as ‘Index.php’ to display output.
Add the following HTML code into ‘Index.php’

hand icon Index.php Code

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>PHP Event Calendar by CodexWorld</title>
    <link type="text/css" rel="stylesheet" href="style.css" />
    <script src="jquery.min.js"></script>
    </head>
    <body>
    <?php include_once('functions.php'); ?>
    <div id="calendar_div">
        <?php echo getCalender(); ?>
    </div>
    </body>
</html>
Copy to Clipboard

NOTE: If you used any Javascript Library, then it is must to add jquery.

For example, you can add jquery like below.

<script src="jquery.min.js"></script>
Copy to Clipboard

Once done, create a new file and name it ‘connection.php’

hand icon Connection.php Code

define('HOST', 'localhost');
define('USERNAME', 'root');
define('PASSWORD', 'ur48x');
define('DATABASE_NAME', 'event_calendar');

//Connect and select the database
$db = new mysqli(HOST, USERNAME, PASSWORD, DATABASE_NAME);

if ($db->connect_error) {
    die("Connection failed: " . $db->connect_error);
}    
Copy to Clipboard

NOTE: change the value of HOST, USERNAME, PASSWORD, and DATABASE_NAME before you run your connection.php file in browser. If you get any error, then it might be due to wrong values.

On completion of above, we’ll create the next file and name it as ‘function.php’

Here, we’ll manage the calendar, add, and view events through a popup according to needs.

The following three functions will be used to perform the calendar operations.

  • getcalendar();
  • get_events_information();
  • add_event_information();

First, we’ll define all three functions.

if(isset($_POST['fun_type']) && !empty($_POST['fun_type'])) {
    switch($_POST['fun_type']) {
        case 'getCalender':
            getCalender($_POST['year'],$_POST['month']);
            break;
        case 'get_events_information':
            get_events_information($_POST['date']);
            break;
        //For Add Event with date wise.
        case 'add_event_information':
            add_event_information($_POST['date'],$_POST['title']);
            break;
        default:
            break;
    }
}   
Copy to Clipboard

NOTE: hand icon get_calendar_full() function is to be accessed from ‘Index.php’ as it’s the default view calendar.

get_calendar _full() function code

function get_calender_full($year = '', $month = '') {
    $date_Year = ($year != '') ? $year : date("Y");
    $date_Month = ($month != '') ? $month : date("m");
    $date = $date_Year.'-'.$date_Month.'-01';
    $current_Month_First_Day = date("N", strtotime($date));
    $total_Days_ofMonth = cal_days_in_month(CAL_GREGORIAN, $date_Month, $date_Year);
    $total_Days_ofMonthDisplay = ($current_Month_First_Day == 7) ? ($total_Days_ofMonth) : ($total_Days_ofMonth + $current_Month_First_Day);
    $boxDisplay = ($total_Days_ofMonthDisplay <= 35) ? 35 : 42;
    ?> 

    <div id="calender_section"> 
        <h2>
        <a href="javascript:void(0);" onclick="get_calendar_data('calendar_div','<?php echo date("Y",strtotime($date.' - 1 Month')); ?>','<?php echo date("m",strtotime($date.' - 1 Month')); ?>');"</a>
            <select name="month_dropdown" class="month_dropdown dropdown"><?php echo get_all_months__of_year($date_Month); ?></select> 
            <select name="year_dropdown" class="year_dropdown dropdown"><?php echo get_year($date_Year); ?></select>
            <a href="javascript:void(0);" onclick="get_calendar_data('calendar_div','<?php echo date("Y",strtotime($date.' + 1 Month')); ?>','<?php echo date("m",strtotime($date.' + 1 Month')); ?>');"</a> 
        </h2> 
        <div id="event_list" class="modal"></div> 
         <!--Below Code for Event Add--> 
         <!-- The Modal --> 
        <div id="event_add" class="modal"> 
            <div class="modal-content">  
            <span class="close"> 
                <a href="#" onclick="close_popup('event_add')">×</ a> 
            </span>  
            <p> Add Event on <span id="eventDateView"</span></p>  
            <p> 
                <b> Event Title: </b> 
                <input type="text" id="eventTitle" value=""/> 
            </p> 
            <input type="hidden" id="eventDate" value=""/>
            <input type="button" id="add_event_informationBtn" value="Add"/>
            </div> 
        </div>
        <div id="calender_section_top"> 
            <ul>
              <li>SUN</li>
              <li>MON</li>
              <li>TUE</li>
              <li>WED</li>
              <li>THU</li>
              <li>FRI</li>
              <li>SAT</li>
            </ul> 
        <div>
        <div id="calender_section_bot"> 
            <ul>
            <?php 
                $dayCount = 1; 
                for($cb=1;$cb<=$boxDisplay;$cb++){ 
                  if(($cb >= $current_Month_First_Day+1 || $current_Month_First_Day == 7) && $cb <= ($total_Days_ofMonthDisplay)){ 
                    // Below javascript code for get current date 
                    $currentDate = $date_Year.'-'.$date_Month.'-'.$dayCount; 
                    $eventNum = 0; 
                    // Below line for including file of database connection file 
                    include 'connection.php'; 
                    // Below query useing for getting number of events in current date 
                    $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 '<li date="'.$currentDate.'" class="grey date_cell">'; 
                    }elseif($eventNum > 0){ 
                      echo '<li date="'.$currentDate.'" class="light_sky date_cell">'; 
                    }else{ 
                      echo '<li date="'.$currentDate.'" class="date_cell">'; 
                }
            //Date cell 
            echo '<span>'; 
            echo '['.$dayCount.']'; 
            echo '</span>'; 
            //Hover event popup 
            echo '<div id="date_popup_'.$currentDate.'" class="date_popup_wrap none">'; 
            echo '<div class="date_window">'; 
            echo '<div class="popup_event">Events ('.$eventNum.')</div>'; 
            echo ($eventNum > 0)?'<a href="javascript:;" onclick="get_events_information(\''.$currentDate.'\');">View Events</a><br/>':''; 
            //For Add Event 
            echo '<a href="javascript:;" onclick="add_event_information(\''.$currentDate.'\');">Add Event</a>'; 
            echo '</div></div>'; 
            echo '</li>'; 
            $dayCount++; 
            ?> 
            <?php }else{ ?> 
            <li><span>&nbsp;</span></li> 
            <?php } } ?> 
            </ul> 
            </div>
            </div>
        <script type="text/javascript"> 
        function get_calendar_data(target_div,year,month){ 
            $.ajax({ 
              type:'POST', 
              url:'functions.php', 
              data:{fun_type:'get_calender_full', year:year, month:month}, 
              success:function(html){ 
                $('#'+target_div).html(html); 
              } 
            }); 
          } 
          
          function get_events_information(date){ 
            $.ajax({ 
              type:'POST', 
              url:'functions.php', 
              data:{fun_type:'get_events_information', date:date}, 
              success:function(html){ 
                $('#event_list').html(html); 
                $('#event_add').slideUp('slow'); 
                $('#event_list').slideDown('slow'); 
              } 
            }); 
          }
          /* 
            * function name add_event_information 
            * Description :- Add Event inforation as per date wise 
            * parameter :- date 
            */ 
            function add_event_information(date){ 
                $('#eventDate').val(date); 
                $('#eventDateView').html(date); 
                $('#event_list').slideUp('slow'); 
                $('#event_add').slideDown('slow'); 
            } 

/* 
    *  below code used to save event information into database. and set message event created successfully. 
    */ 
    $(document).ready(function(){ 
        $('#add_event_informationBtn').on('click',function(){  
            var date = $('#eventDate').val(); 
            var title = $('#eventTitle').val(); 
            $.ajax({ 
                type:'POST',  
                url:'functions.php',  
                data:{fun_type:'add_event_information', date:date, title:title},  
                success:function(msg){ 
                    if(msg == 'ok'){  
                        var dateSplit = date.split("-");  
                        $('#eventTitle').val(''); 
                        alert('Event Created.'); 
                        get_calendar_data('calendar_div',dateSplit[0],dateSplit[1]); 
                     }else  {  
                        alert('Sorry some issues please try again later.');  
                    } 
                } 
            }); 
        }); 
    }); 
    
    $(document).ready(function(){ 
        $('.date_cell').mouseenter(function(){ 
            date = $(this).attr('date'); 
            $(".date_popup_wrap").fadeOut(); 
            $("#date_popup_"+date).fadeIn();
        }); 
        $('.date_cell').mouseleave(function(){ 
            $(".date_popup_wrap").fadeOut();
        }); 
        $('.month_dropdown').on('change',function(){  
            get_calendar_data('calendar_div',$('.year_dropdown').val(),$('.month_dropdown').val()); 
        }); 
        $('.year_dropdown').on('change',function(){ 
            get_calendar_data('calendar_div',$('.year_dropdown').val(),$('.month_dropdown').val()); 
        });  
        $(document).click(function(){  
            $('#event_list').slideUp('slow');  
        }); 
    }); 
    
// Closed popup string
function close_popup(event_id) { 
    $('#'+event_id).css('display','none'); 
} 
</script> 
<?php 
} ?>
Copy to Clipboard

Want to Create a Web Application?

Need to validate your app idea or consult with an expert? Get a free consultation now!

Cta Image

hand icon get_events_information() function code

/********************************************

* below function used for display event as per date 
* optional parameter is date. *******************************************/ 

function get_events_information($date = '') { 

    //below line for including file of database connection file 
    include 'connection.php'; 

    $eventListHTML = ''; 
    $date = $date ? $date : date("Y-m-d"); 

    //Get events based on the current date 
    $result = $db->query("SELECT title FROM events WHERE date = '".$date."' AND status = 1"); 

    if($result->num_rows > 0) { 
        $eventListHTML .= '<div class="modal-content">'; 
        $eventListHTML .= '<span class="close"><a href="#" onclick="close_popup("event_list")">×</a></span>'; 
        $eventListHTML .= '<h2>Events on '.date("l, d M Y",strtotime($date)).'<h2>'; 
        $eventListHTML .= '<ul>'; 
        while($row = $result->fetch_assoc()) { 
            $eventListHTML .= '<li>'.$row['title'].'</li>'; 
        } 
        $eventListHTML .= '</ul>'; 
        $eventListHTML .= '</div>'; 
    } 

    echo $eventListHTML; 
}    
Copy to Clipboard

hand icon add_event_information() function code

/********************************************************** 

* below function is used to add event in particular date 
* parameter is >>> date , title 
**********************************************************/ 

function add_event_information($date, $title) { 
    //below line for including file of database connection file 
    include 'connection.php'; 

    $currentDate = date("Y-m-d H:i:s"); 

    //Insert the event data into database 
    $insert = $db->query("INSERT INTO events (title,date,created,modified) VALUES ('".$title."','".$date."','".$currentDate."','".$currentDate."')"); 

    if($insert) { 
        echo 'ok'; 
    } else { 
        echo 'err'; 
    } 
}
Copy to Clipboard

Testing

Now once you run the ‘Index.php’, you’ll see a calendar like below.

calendra_view

Here, you can change your desired year and month. The green background indicates today’s date.

When you hover over a cell, two options will popup: one to add event and another to view events.

date_hover_effect

On clicking ‘add event’ option, a popup will appear with textbox and button to add event.

add_event

To view created events, hover over on the date cell where you created events and click on ‘View Events’

event_listing

And done!

This is how you can add the same PHP Calendar Event feature in your site. However, it’s also possible to add more such features while developing a website. It’s beneficial as well, in many ways. So take this feature in consideration, hire PHP developers if needed, and implement in your website.

If you know how to use JQuery and Ajax then you can also improve form validation on your PHP website by providing users feedback on any errors in their input. To implement this go through our post on how to submit form using ajax in PHP. Doing so will help for better user interface and experience of your website.

Grab a free copy of Calendar using javascript demo from Github.

We hope you found this tutorial helpful in creating a PHP event calendar with JQuery and Ajax to manage events. If you are still unsure about implementing this feature on your own, consider hiring a reputable PHP development company like ours to help you. Our skilled developers can assist you in integrating a fully functional event calendar into your website and customising it to meet your specific requirements.

Bhaval Patel

Written by

Bhaval Patel is a Director (Operations) at Space-O Technologies. He has 20+ years of experience helping startups and enterprises with custom software solutions to drive maximum results. Under his leadership, Space-O has won the 8th GESIA annual award for being the best mobile app development company. So far, he has validated more than 300 app ideas and successfully delivered 100 custom solutions using the technologies, such as Swift, Kotlin, React Native, Flutter, PHP, RoR, IoT, AI, NFC, AR/VR, Blockchain, NFT, and more.