PHP AJAX Calendar

Tutorials

The php calendar is an integral part of many websites, frequently, this is one of numerous jQuery calendar plugins, but it can also be implemented using php. Today I will show you how to create a monthly calendar with the ability to scroll (left and right arrows) through the months using AJAX technology. Besides of ajax, this calendar has another important advantage, it is mobile-ready calendar with the responsive layout. Before we start writing code, I recommend that you look at our demo to see what we’re going to do.

Preview

PHP AJAX Calendar

Live Demo

Folder structure

In the beginning, let’s define a clear folder structure for all of our following files

  • css – for all css files
  • images – for all possible images
  • templates – for all template files

Step 1. HTML

We are not going to use any specific template system (like Smarty), we are only about to use simple html templates with own replacement keys

templates/index.html

01 <!DOCTYPE html>
02 <html lang="en">
03 <head>
04     <meta charset="utf-8" />
05     <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
06     <title>PHP AJAX Calendar</title>
07     <!-- add styles and scripts -->
08     <link href="css/styles.css" rel="stylesheet" type="text/css" />
10 </head>
11 <body>
12     <div id="calendar">
13         __calendar__
14     </div>
15 </body>
16 </html>

This is a very simple template for our index page where we defined the parent container for our calendar. Another template will be used as an inner container of the calendar:

templates/calendar.html

01 <div class="navigation">
02     <a class="prev" href="index.php?month=__prev_month__" onclick="$('#calendar').load('index.php?month=__prev_month__&_r=' + Math.random()); return false;"></a>
03     <div class="title" >__cal_caption__</div>
04     <a class="next" href="index.php?month=__next_month__" onclick="$('#calendar').load('index.php?month=__next_month__&_r=' + Math.random()); return false;"></a>
05 </div>
06 <table>
07     <tr>
08         <th class="weekday">sun</th>
09         <th class="weekday">mon</th>
10         <th class="weekday">tue</th>
11         <th class="weekday">wed</th>
12         <th class="weekday">thu</th>
13         <th class="weekday">fri</th>
14         <th class="weekday">sat</th>
15     </tr>
16     __cal_rows__
17 </table>

The reason is that in case of ajax requests we are not required to return everything, except the internal calendar content.

Step 2. PHP

The time for action

index.php

01 // Get current year, month and day
02 list($iNowYear$iNowMonth$iNowDay) = explode('-'date('Y-m-d'));
03 // Get current year and month depending on possible GET parameters
04 if (isset($_GET['month'])) {
05     list($iMonth$iYear) = explode('-'$_GET['month']);
06     $iMonth = (int)$iMonth;
07     $iYear = (int)$iYear;
08 else {
09     list($iMonth$iYear) = explode('-'date('n-Y'));
10 }
11 // Get name and number of days of specified month
12 $iTimestamp mktime(0, 0, 0, $iMonth$iNowDay$iYear);
13 list($sMonthName$iDaysInMonth) = explode('-'date('F-t'$iTimestamp));
14 // Get previous year and month
15 $iPrevYear $iYear;
16 $iPrevMonth $iMonth - 1;
17 if ($iPrevMonth <= 0) {
18     $iPrevYear--;
19     $iPrevMonth = 12; // set to December
20 }
21 // Get next year and month
22 $iNextYear $iYear;
23 $iNextMonth $iMonth + 1;
24 if ($iNextMonth > 12) {
25     $iNextYear++;
26     $iNextMonth = 1;
27 }
28 // Get number of days of previous month
29 $iPrevDaysInMonth = (int)date('t'mktime(0, 0, 0, $iPrevMonth$iNowDay$iPrevYear));
30 // Get numeric representation of the day of the week of the first day of specified (current) month
31 $iFirstDayDow = (int)date('w'mktime(0, 0, 0, $iMonth, 1, $iYear));
32 // On what day the previous month begins
33 $iPrevShowFrom $iPrevDaysInMonth $iFirstDayDow + 1;
34 // If previous month
35 $bPreviousMonth = ($iFirstDayDow > 0);
36 // Initial day
37 $iCurrentDay = ($bPreviousMonth) ? $iPrevShowFrom : 1;
38 $bNextMonth = false;
39 $sCalTblRows '';
40 // Generate rows for the calendar
41 for ($i = 0; $i < 6; $i++) { // 6-weeks range
42     $sCalTblRows .= '<tr>';
43     for ($j = 0; $j < 7; $j++) { // 7 days a week
44         $sClass '';
45         if ($iNowYear == $iYear && $iNowMonth == $iMonth && $iNowDay == $iCurrentDay && !$bPreviousMonth && !$bNextMonth) {
46             $sClass 'today';
47         elseif (!$bPreviousMonth && !$bNextMonth) {
48             $sClass 'current';
49         }
50         $sCalTblRows .= '<td class="'.$sClass.'"><a href="javascript: void(0)">'.$iCurrentDay.'</a></td>';
51         // Next day
52         $iCurrentDay++;
53         if ($bPreviousMonth && $iCurrentDay $iPrevDaysInMonth) {
54             $bPreviousMonth = false;
55             $iCurrentDay = 1;
56         }
57         if (!$bPreviousMonth && !$bNextMonth && $iCurrentDay $iDaysInMonth) {
58             $bNextMonth = true;
59             $iCurrentDay = 1;
60         }
61     }
62     $sCalTblRows .= '</tr>';
63 }
64 // Prepare replacement keys and generate the calendar
65 $aKeys array(
66     '__prev_month__' => "{$iPrevMonth}-{$iPrevYear}",
67     '__next_month__' => "{$iNextMonth}-{$iNextYear}",
68     '__cal_caption__' => $sMonthName ', ' $iYear,
69     '__cal_rows__' => $sCalTblRows,
70 );
71 $sCalendarItself strtr(file_get_contents('templates/calendar.html'), $aKeys);
72 // AJAX requests - return the calendar
73 if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && isset($_GET['month'])) {
74     header('Content-Type: text/html; charset=utf-8');
75     echo $sCalendarItself;
76     exit;
77 }
78 $aVariables array(
79     '__calendar__' => $sCalendarItself,
80 );
81 echo strtr(file_get_contents('templates/index.html'), $aVariables);

I tried to comment on every single line of code in order to let you understand the whole process. In the beginning we make date-related calculations with current date and requested dates. Then, we generate the calendar rows (days), finally, we replace the template keys to values. On Ajax requests, we return only the inner content ($sCalendarItself), otherwise – we display the whole page

Step 3. CSS

At the moment, our calendar does not look properly because it is just a bare html code. Let’s decorate our calendar

css/styles.css

01 /* calendar styles */
02 #calendar {
03     -moz-user-select: none;
04     border1px solid #EEEEEE;
05     border-radius: 6px 6px 6px 6px;
06     color#333333;
07     font-familyArial,sans-serif;
08     font-size1.1em;
09     margin10px auto;
10     padding0.4em;
11     width90%;
12 }
13 #calendar .navigation {
14     background-color#CC0000;
15     border1px solid #E3A1A1;
16     border-radius: 6px 6px 6px 6px;
17     color#FFFFFF;
18     font-weightbold;
19     padding1px;
20     positionrelative;
21 }
22 #calendar .navigation .title {
23     backgroundnone repeat scroll 0 0 transparent;
24     border-color: rgba(0000);
25     color: inherit;
26     line-height1.8em;
27     margin0 2.3em;
28     text-aligncenter;
29 }
30 #calendar .navigation .prev, #calendar .navigation .next {
31     background-imageurl(../images/nav.png);
32     height24px;
33     opacity: 0.9;
34     positionabsolute;
35     top4px;
36     width24px;
37 }
38 #calendar .navigation .prev {
39     background-position0 0;
40     left4px;
41 }
42 #calendar .navigation .next {
43     background-position-24px 0;
44     right4px;
45 }
46 #calendar .navigation .prev:hover, #calendar .navigation .next:hover {
47     opacity: 1;
48 }
49 #calendar table {
50     border-collapsecollapse;
51     font-size0.9em;
52     table-layoutfixed;
53     width100%;
54 }
55 #calendar table th {
56     border0 none;
57     font-weightbold;
58     padding0.7em 0.3em;
59     text-aligncenter;
60 }
61 #calendar table td {
62     border0 none;
63     padding1px;
64 }
65 #calendar table td a {
66     background-color#EEEEEE;
67     border1px solid #D8DCDF;
68     color#004276;
69     displayblock;
70     font-weightnormal;
71     opacity: 0.7;
72     padding0.2em;
73     text-alignright;
74     text-decorationnone;
75 }
76 #calendar table td a:hover {
77     background-color#F6F6F6;
78     border1px solid #CDD5DA;
79     color#111111;
80 }
81 #calendar table td.current a {
82     font-weightbold;
83     opacity: 1;
84 }
85 #calendar table td.today a {
86     background-color#FBF8EE;
87     border1px solid #FCD3A1;
88     color#444444;
89     font-weightbold;
90     opacity: 1;
91 }

Step 4. Images

Only one small image is used in the styles of our calendar: nav.png

PHP AJAX Calendar


Live Demo

[sociallocker]

download the sources

[/sociallocker]


Conclusion

That’s all for today, we have just prepared stylish responsive calendar. Thanks for your patient attention, and if you really like what we did today – share it with all your friends in your social networks using the form below.

Rate article