HOW TO PHP EVENT CALENDER WITH JQUERY AJAX

HOW TO PHP EVENT CALENDER WITH JQUERY AJAX

HOW TO PHP EVENT CALENDER WITH JQUERY AJAX

0 Sales

Free

 

Event calendar provides an easy-to-use way to list events by date. It helps the user to quickly find the events for a specific date. The event calendar is a useful feature in the web application to show events datewise. Specific jQuery plugins are available to incorporate the website activity calendar. But if you want to list dynamic events on the calendar, PHP can easily be used to integrate them.

 

PHP Event Calendar helps in the calendar date cell to collect dynamic data from the database and list events. You may link the event to the calendar together with the corresponding date using the PHP event calendar. In this tutorial, we'll show you how to use jQuery, Ajax, PHP, and MySQL to create an event calendar.

 

To create PHP event calendar, the following functionality will be implemented.

 

  • Fetch data from the MySQL database for events.

  • Create an extensive HTML and CSS calendar.

  • Display events in the calendar's date cell.

  • Using jQuery and Ajax to move between the months.

 

Before you start, take a look at the PHP event calendar script's files structure.


 

php_event_calendar/

├── dbConfig.php

├── functions.php

├── logout.php

├── js/

│   └── jquery.min.js

├── css/

│   └── style.css

└── images/

    └── info-popup.png

 

Create Database Table


 

The event information must be stored in the server in order to display the complex events in the calendar. The following SQL creates a table of events in the MySQL database with a few basic fields.

 

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)

 

Using PHP and MySQL, this directory is used to link to the server. Specify for your database credentials the database host ($dbHost), username ($dbUsername), password ($dbPassword), and name ($dbName).

 

<?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 Event Calendar (functions.php)

 

The functions.php file contains all the functions used to generate a PHP and MySQL event calendar.

 

  1. GetCalender() 

  • –Generate a calendar based on the month and year in question.

  •  Collect events from the database and add events to the calendar date cell.

  1. GetAllMonths() –Create the select box option list for months to drop down.

  2. GetYearList() –Create a select box year option list that is used for years of dropdown.

  3. GetEvents() –Get events from the database by date and return the list of events as an HTML format.


<?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; 

        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 == 7)?($totalDaysOfMonth):($totalDaysOfMonth + $currentMonthFirstDay); 

    $boxDisplay = ($totalDaysOfMonthDisplay <= 35)?35:42; 

?> 

    <div class="calendar-wrap"> 

        <div class="cal-nav"> 

            <a href="javascript:void(0);" onclick="getCalendar('calendar_div','<?php echo date("Y",strtotime($date.' - 1 Month')); ?>','<?php echo date("m",strtotime($date.' - 1 Month')); ?>');">&laquo;</a> 

            <select class="month_dropdown"><?php echo getAllMonths($dateMonth); ?></select> 

            <select class="year_dropdown"><?php echo getYearList($dateYear); ?></select> 

            <a href="javascript:void(0);" onclick="getCalendar('calendar_div','<?php echo date("Y",strtotime($date.' + 1 Month')); ?>','<?php echo date("m",strtotime($date.' + 1 Month')); ?>');">&raquo;</a> 

        </div> 

        <div id="event_list" class="none"></div> 

        <div class="calendar-days"> 

            <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 class="calendar-dates"> 

            <ul> 

            <?php  

                $dayCount = 1; 

                $eventNum = 0; 

                for($cb=1;$cb<=$boxDisplay;$cb++){ 

                    if(($cb >= $currentMonthFirstDay+1 || $currentMonthFirstDay == 7) && $cb <= ($totalDaysOfMonthDisplay)){ 

                        // Current date 

                        $currentDate = $dateYear.'-'.$dateMonth.'-'.$dayCount; 

                      

                        // Include the database config file 

                        include_once 'dbConfig.php'; 

                      

                        // Get number of events based on the 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="getEvents(\''.$currentDate.'\');">view events</a>':''; 

                        echo '</div></div>'; 

                      

                        echo '</li>'; 

                        $dayCount++; 

            ?> 

            <?php }else{ ?> 

                <li><span>&nbsp;</span></li> 

            <?php } } ?> 

            </ul> 

        </div> 

    </div> 

 

    <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); 

                    $('#event_list').slideDown('slow'); 

                } 

            }); 

        } 

      

        $(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(){ 

                getCalendar('calendar_div', $('.year_dropdown').val(), $('.month_dropdown').val()); 

            }); 

            $('.year_dropdown').on('change',function(){ 

                getCalendar('calendar_div', $('.year_dropdown').val(), $('.month_dropdown').val()); 

            }); 

            $(document).click(function(){ 

                $('#event_list').slideUp('slow'); 

            }); 

        }); 

    </script> 

<?php 

} 

 

/* 

 * Generate months options list for select box 

 */ 

function getAllMonths($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(0, 0, 0, $i+1, 0, 0)).'</option>'; 

    } 

    return $options; 

} 

 

/* 

 * Generate years options list for select box 

 */ 

function getYearList($selected = ''){ 

    $options = ''; 

    for($i=2019;$i<=2025;$i++) 

    { 

        $selectedOpt = ($i == $selected)?'selected':''; 

        $options .= '<option value="'.$i.'" '.$selectedOpt.' >'.$i.'</option>'; 

    } 

    return $options; 

} 

 

/* 

 * Generate events list in HTML format 

 */ 

function getEvents($date = ''){ 

    // Include the database config file 

    include_once 'dbConfig.php'; 

  

    $eventListHTML = ''; 

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

  

    // Fetch events based on the specific date 

    $result = $db->query("SELECT title FROM events WHERE date = '".$date."' AND status = 1"); 

    if($result->num_rows > 0){ 

        $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>'; 

    } 

    echo $eventListHTML; 

}

 

Display Event Calendar (index.php)


 

To view the event calendar on the web page, call the getCalender() function.

 

  • Include the support function folder (functions.php).

  • Use the function getCalender) (to add calendar to the web page.

  • Using AJAX request, the respective events are loaded upon date change, so include the library jQuery.

 

<?php 

// Include calendar helper functions 

include_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>

</head>

<body>

<!-- Display event calendar -->

<div id="calendar_div">

<?php echo getCalender(); ?>

</div>

</body>

</html>


 

Testing

Open the browser's index.php file, you will see the calendar appearing like the screen below. Today's date would have a gray background and if the respective date has events, dates would have a sky color background. You can also change from the top of the calendar your desired year and month. The events will be loaded with jQuery and Ajax without page refresh by changing the year, month, and date.

LICENSE OF USE

You can use it for personal or commercial projects. You can't resell it partially or in this form.

PRODUCT INFO

Create Date : May 14, 2020

Updated Date : May 14, 2020

Ratings

Comments : 0

Downloads : 0