YouTube Icon

Code Playground.

How to Implement Event Calendar in CodeIgniter Using jQuery

CFG

How to Implement Event Calendar in CodeIgniter Using jQuery

Event Calendar assists with posting the Events in an easy to understand way. The full view schedule is the best choice to show the Events in a schedule. In the dynamic web application, the Events are brought from the database and recorded in the enormous schedule. The dynamic Event schedule can be handily worked with PHP and MySQL. 

On the off chance that your web application worked with the CodeIgniter system, the Event schedule usefulness needs to incorporate into the CodeIgniter application. You can without much of a stretch make a custom Event schedule to show Events from the database in CodeIgniter. Right now, will tell you the best way to construct an Event schedule in CodeIgniter utilizing jQuery and Ajax.

In the sample CodeIgniter Event Calendar, the following functionality will be implemented.

  • Fetch events data from the MySQL database.
  • Create a full-view calendar with HTML and CSS.
  • Display events in the date cell of the calendar.
  • Navigate between the months and years using jQuery and Ajax.

Create Database Table

To store the dynamic events data a table is required 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;

Controller (Calendar.php)

The Calendar controller helps to generate event calendar and display calendar in the full view.

  • __construct() – Load the Event model.
  • index() –
    • Get event calendar using eventCalendar() method.
    • Pass the calendar HTML to the view.
  • eventCalendar() –
    • Build event calendar based on the year and month.
    • Load calendar view.
  • getMonths() – Generate months options list for the select box.
  • getYears() – Generate years options list for the select box.
  • getEvents() –
    • Fetch events from the database using getRows() method of the Event model.
    • Generate an HTML view of the event lists.
<?php defined('BASEPATH') OR exit('No direct script access allowed'); 
 
class Calendar extends CI_Controller { 
     
    function __construct() { 
        parent::__construct(); 
         
        $this->load->model('event'); 
    } 
     
    public function index(){ 
        $data = array(); 
        $data['eventCalendar'] = $this->eventCalendar(); 
        $this->load->view('calendar/index', $data); 
    } 
     
    public function eventCalendar($year = '', $month = ''){ 
        $data = array(); 
         
        $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; 
         
        $con = array( 
            'where' => array( 
                'status' => 1 
            ), 
            'where_year' => $dateYear, 
            'where_month' => $dateMonth 
        ); 
        $data['events'] = $this->event->getGroupCount($con); 
         
        $data['calendar'] = array( 
            'dateYear' => $dateYear, 
            'dateMonth' => $dateMonth, 
            'date' => $date, 
            'currentMonthFirstDay' => $currentMonthFirstDay, 
            'totalDaysOfMonthDisplay' => $totalDaysOfMonthDisplay, 
            'boxDisplay' => $boxDisplay 
        ); 
         
        $data['monthOptions'] = $this->getMonths($dateMonth); 
        $data['yearOptions'] = $this->getYears($dateYear); 
 
        if(!empty($_SERVER['HTTP_X_REQUESTED_WITH'])){ 
            $this->load->view('calendar/event-cal', $data); 
        }else{ 
            return $this->load->view('calendar/event-cal', $data, true); 
        } 
    } 
     
    function getMonths($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; 
    } 

    function getYears($selected = ''){ 
        $options = ''; 
        for($i=2019;$i<=2025;$i++) 
        { 
            $selectedOpt = ($i == $selected)?'selected':''; 
            $options .= '<option value="'.$i.'" '.$selectedOpt.' >'.$i.'</option>'; 
        } 
        return $options; 
    } 
    
    function getEvents($date = ''){ 
        $eventListHTML = ''; 
        $date = $date?$date:date("Y-m-d"); 
         
        // Fetch events based on the specific date 
        $con = array( 
            'where' => array( 
                'date' => $date, 
                'status' => 1 
            ) 
        ); 
        $events = $this->event->getRows($con); 
 
        if(!empty($events)){ 
            $eventListHTML = '<h2>Events on '.date("l, d M Y",strtotime($date)).'</h2>'; 
            $eventListHTML .= '<ul>'; 
            foreach($events as $row){  
                $eventListHTML .= '<li>'.$row['title'].'</li>'; 
            } 
            $eventListHTML .= '</ul>'; 
        } 
        echo $eventListHTML; 
    } 
}

Model (Event.php)

The Event model handles the database related operations.

  • __construct() – Define the table name.
  • getRows() – Fetch the events data from the database based on the conditions specified in $params. Returns the data array on success, and FALSE on error.
  • getGroupCount() – Grouped by the events based on the date and returns data with event number for each date.
<?php defined('BASEPATH') OR exit('No direct script access allowed'); 
 
class Event extends CI_Model{ 
    function __construct() { 
        // Set table name 
        $this->table = 'events'; 
    } 

    function getRows($params = array()){ 
        $this->db->select('*'); 
        $this->db->from($this->table); 
         
        if(array_key_exists("where", $params)){ 
            foreach($params['where'] as $key => $val){ 
                $this->db->where($key, $val); 
            } 
        } 
         
        if(array_key_exists("returnType",$params) && $params['returnType'] == 'count'){ 
            $result = $this->db->count_all_results(); 
        }else{ 
            if(array_key_exists("id", $params) || (array_key_exists("returnType", $params) && $params['returnType'] == 'single')){ 
                if(!empty($params['id'])){ 
                    $this->db->where('id', $params['id']); 
                } 
                $query = $this->db->get(); 
                $result = $query->row_array(); 
            }else{ 
                $this->db->order_by('date', 'asc'); 
                if(array_key_exists("start",$params) && array_key_exists("limit",$params)){ 
                    $this->db->limit($params['limit'],$params['start']); 
                }elseif(!array_key_exists("start",$params) && array_key_exists("limit",$params)){ 
                    $this->db->limit($params['limit']); 
                } 
                 
                $query = $this->db->get(); 
                $result = ($query->num_rows() > 0)?$query->result_array():FALSE; 
            } 
        } 
         
        // Return fetched data 
        return $result; 
    } 
     
    function getGroupCount($params = array()){ 
        $this->db->select("date, COUNT(id) as event_num"); 
        $this->db->from($this->table); 
         
        if(array_key_exists("where", $params)){ 
            foreach($params['where'] as $key => $val){ 
                $this->db->where($key, $val); 
            } 
        } 
         
        if(array_key_exists("where_year", $params)){ 
            $this->db->where("YEAR(date) = ".$params['where_year']); 
        } 
         
        if(array_key_exists("where_month", $params)){ 
            $this->db->where("MONTH(date) = ".$params['where_month']); 
        } 
         
        $this->db->group_by('date'); 
         
        $query = $this->db->get(); 
        $result = ($query->num_rows() > 0)?$query->result_array():FALSE; 
         
        // Return fetched data 
        return $result; 
    } 
}

View

1. calendar/

1.1. index.php
Display the event calendar passed by the index() method of the Calendar controller.

<!-- Display event calendar -->
<div id="calendar_div">
    <?php echo $eventCalendar; ?>
</div>

Include the jQuery library.

<!-- jQuery library -->
<script src="<?php echo base_url('assets/js/jquery.min.js'); ?>"></script>

The following code is used to get the calendar and events data using jQuery and Ajax.

  • The getCalendar() function Initiate Ajax request to get calendar HTML from eventCalendar() method of Calendar controller.
  • The getEvents() function Initiate Ajax request to get events list from getEvents() method of Calendar controller.
<script>
function getCalendar(target_div, year, month){
    $.get( '<?php echo base_url('calendar/eventCalendar/'); ?>'+year+'/'+month, function( html ) {
        $('#'+target_div).html(html);
    });
}

function getEvents(date){
    $.get( '<?php echo base_url('calendar/getEvents/'); ?>'+date, function( html ) {
        $('#event_list').html(html);
        $('#event_list').slideDown('slow');
    });
}
</script>

The following code shows the dialog over the date cell to show the events number. Also, helps to change the calendar days by changing the year or month dropdown.

<script>
$(document).on("mouseenter", ".date_cell", function(){
    date = $(this).attr('date');
    $(".date_popup_wrap").fadeOut();
    $("#date_popup_"+date).fadeIn();
});
$(document).on("mouseleave", ".date_cell", function(){
    $(".date_popup_wrap").fadeOut();
});
$(document).on("change", ".month_dropdown", function(){
    getCalendar('calendar_div', $('.year_dropdown').val(), $('.month_dropdown').val());
});
$(document).on("change", ".year_dropdown", function(){
    getCalendar('calendar_div', $('.year_dropdown').val(), $('.month_dropdown').val());
});
$(document).click(function(){
    $('#event_list').slideUp('slow');
});
</script>

1.2. event-cal.php
Create a large calendar and add events to this calendar.

  • In the header, year and month dropdown is provided to navigate to the different month.
  • Next and Prev button is provided to navigate to the next and previous month.
  • Each date cell holds the number of the events. On hover, a tooltip appears with the event number for the selected date.
  • By clicking the event number, the events are listed at the top of the calendar.
<div class="calendar-wrap">
    <div class="cal-nav">
        <a href="javascript:void(0);" onclick="getCalendar('calendar_div','<?php echo date("Y",strtotime($calendar['date'].' - 1 Month')); ?>','<?php echo date("m",strtotime($calendar['date'].' - 1 Month')); ?>');">&laquo;</a>
        <select class="month_dropdown"><?php echo $monthOptions; ?></select>
        <select class="year_dropdown"><?php echo $yearOptions; ?></select>
        <a href="javascript:void(0);" onclick="getCalendar('calendar_div','<?php echo date("Y",strtotime($calendar['date'].' + 1 Month')); ?>','<?php echo date("m",strtotime($calendar['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<=$calendar['boxDisplay'];$cb++){ 
                if(($cb >= $calendar['currentMonthFirstDay']+1 || $calendar['currentMonthFirstDay'] == 7) && $cb <= ($calendar['totalDaysOfMonthDisplay'])){ 
                    // Current date 
                    $dayCount = ($dayCount < 10 && strpos($dayCount, '0') == false)?'0'.$dayCount:$dayCount; 
                    $currentDate = $calendar['dateYear'].'-'.$calendar['dateMonth'].'-'.$dayCount; 
                     
                    // Get number of events based on the current date 
                    $eventNum = 0; 
                    if(!empty($events)){ 
                        $eventData = array_filter($events, function ($var) use ($currentDate) { 
                            return ($var['date'] == $currentDate); 
                        }); 
                        $eventData = array_values($eventData); 
                        $eventData = !empty($eventData[0])?$eventData[0]:''; 
                        $eventNum = !empty($eventData['event_num'])?$eventData['event_num']:0; 
                    } 
                     
                    // 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>

Conclusion

Our model code encourages you to coordinate the Event schedule usefulness in the CodeIgniter site. The Events can be shown in the schedule powerfully from the database. This schedule permits exploring to the diverse month without page invigorate utilizing jQuery and Ajax. You can without much of a stretch improve the usefulness of the CodeIgniter Event schedule according to your necessities. 




CFG