7 min read

There are many reasons why you would want to display a calendar. You can use it to display upcoming events, to keep a diary, or to show a timetable. Recently, for example, I combined a calendar with an online store for a client to book meetings and receive payments more intuitively.

Google calendar is probably what springs to mind when people think of calendars online. There is a very good plugin called jquery-week-calendar that shows a week with events in a fashion similar to Google’s calendar.

Calendars in jQuery 1.3 with PHP using jQuery Week Calendar Plugin: Part 1

Its homepage is at http://www.redredred.com.au/projects/jquery-week-calendar/.

To get the latest copy of the plugin, go to http://code.google.com/p/jquery-week-calendar/downloads/list and get the highest-numbered file. The examples in this article are done with version 1.2.0.

Download the library and extract it so that there is a directory named jquery-weekcalendar-1.2.0 in the root of your demo directory.

Displaying the calendar

As usual, the HTML for the simplest configuration is very simple. Save this as calendar.html:







href="../jquery-ui.css" />
href="../jquery-weekcalendar-1.2.0/jquery.weekcalendar.css"/>





We will keep all of our JavaScript in an external file called calendar.js, which will initially contain just this:

$(document).ready(function() { 
$('#calendar_wrapper').weekCalendar({
'height':function($calendar){
return $('#calendar_wrapper')[0].offsetHeight;
}
});
});

This is fairly straightforward. The script will apply the widget to the #calendar_wrapper element, and the widget’s height will be set to that of the wrapper element.

Even with this tiny bit of code, we already have a good-looking calendar, and when you drag your mouse cursor around it, you’ll see that events are created as you lift the mouse up:

Calendars in jQuery 1.3 with PHP using jQuery Week Calendar Plugin: Part 1

It looks good, but it doesn’t do anything yet. The events are temporary, and will vanish as soon as you change the week or reload the page. In order to make them permanent, we need to send details of the events to the server and save them there.

Creating an event

What we need to do is to have the client save the event on the server when it is created.

In this article, we’ll use PHP sessions to save the data for the sake of simplicity.

Sessions are chunks of data, which are kept on the server side and are related to the cookie or PHPSESSID parameter that the client uses to access that session. We will use sessions in these examples because they do not need as much setup as databases.

For your own projects, you should adapt the PHP side in order to connect to a database instead.

If you are using this article to create a full application, you will obviously want to use something more permanent than sessions, in which case the PHP code should be adapted such that all references to sessions are replaced with database references instead. This is beyond the scope of this book, but as you are a PHP developer, you probably do this everyday anyway!

When the event has been created, we want a modal dialog to appear and ask for more details. In this test case, we’ll add a text area for further details, which allows for more data than would appear in the small visible area in the calendar itself.

A modal dialog is a “pop up” that appears and blocks all other actions on the page until it has been taken care of. It’s useful in cases where the answer to a question must be known before a script can carry on with its work.

Now, let’s create an event and add it to our calendar.

Client-side code

In the calendar.js file, add an eventNew event to the weekCalendar call:

$(document).ready(function() { 
$('#calendar_wrapper').weekCalendar({
'height':function($calendar){
return $('#calendar_wrapper')[0].offsetHeight;
},
'eventNew':function(calEvent, $event) {
calendar_new_entry(calEvent,$event);
}
});
});

When an event is created, the calendar_new_entry function will be called with details of the new event in the calEvent parameter.

Now, add the function calendar_new_entry:

function calendar_new_entry(calEvent,$event){ 
var ds=calEvent.start, df=calEvent.end;
$('

event name




body text


').appendTo($('body'));
$("#calendar_new_entry_form").dialog({
bgiframe: true,
autoOpen: false,
height: 440,
width: 450,
modal: true,
buttons: {
'Save': function() {
var $this=$(this);
$.getJSON('./calendar.php?action=save&id=0&start='
+ds.getTime()/1000+'&end='+df.getTime()/1000,
{
'body':$('#calendar_new_entry_form_body').val(),
'title':$('#calendar_new_entry_form_title').val()
},
function(ret){
$this.dialog('close');
$('#calendar_wrapper').weekCalendar('refresh');
$("#calendar_new_entry_form").remove();
}
);
},
Cancel: function() {
$event.remove();
$(this).dialog('close');
$("#calendar_new_entry_form").remove();
}
},
close: function() {
$('#calendar').weekCalendar('removeUnsavedEvents');
$("#calendar_new_entry_form").remove();
}
});
$("#calendar_new_entry_form").dialog('open');
}

What’s happening here is that a form is created and added to the body (the second line of the function), then the third line of the function creates a modal window from that form and adds some buttons to it.

Our modal dialog should look like this:

Calendars in jQuery 1.3 with PHP using jQuery Week Calendar Plugin: Part 1

The Save button, when pressed, calls the server-side file calendar.php with the parameters needed to save the event, including the start and end, and the title and body.

When the result returns, the calendar is refreshed with the new event’s data included.

When any of the buttons are clicked, we close the dialog and remove it from the page completely.

Note how we are sending time information to the server (shown highlighted in the code we just saw). JavaScript time functions usually measure in milliseconds, but we want to send it to PHP, which generally measures time in seconds. So, we convert the value on the client so that the PHP can use the received data as it is, without needing to do anything to it. Every little helps!

Server-side code

On the server side, we want to take the new event and save it. Remember that we’re doing it in sessions in this example, but you should feel free to adapt this to any other model that you wish.

Create a file called calendar.php and save it with this source in it:

  session_start(); 
if(!isset($_SESSION['calendar'])){
$_SESSION['calendar']=array(
'ids'=>0,
);
}
if(isset($_REQUEST['action'])){
switch($_REQUEST['action']){
case 'save': // {
$start_date=(int)$_REQUEST['start'];
$data=array(
'title'=>(isset($_REQUEST['title'])?$_REQUEST['title']:''),
'body' =>(isset($_REQUEST['body'])?$_REQUEST['body']:''),
'start'=>date('c',$start_date),
'end' =>date('c',(int)$_REQUEST['end'])
);
$id=(int)$_REQUEST['id'];
if($id && isset($_SESSION['calendar'][$id])){
$_SESSION['calendar'][$id]=$data;
}
else{
$id= ++$_SESSION['calendar']['ids'];
$_SESSION['calendar'][$id]=$data;
}
echo 1;
exit;
// }
}
}
?>

In the server-side code of this project, all the requested actions are handled by a switch statement. This is done for demonstration purposes—whenever we add a new action, we simply add a new switch case. If you are using this for your own purposes, you may wish to rewrite it using functions instead of large switch cases.

The date function is used to convert the start and end parameters into ISO 8601 date format. That’s the format jquery-week-calendar prefers, so we’ll try to keep everything in that format.

Visually, nothing appears to happen, but the data is actually being saved.

To see what’s being saved, create a new file named test.php, and use the var_dump function in it to examine the session data (view it in your browser):

session_start(); 
var_dump($_SESSION);
?>

Here’s an example from my test machine:


Subscribe to the weekly Packt Hub newsletter. We'll send you this year's Skill Up Developer Skills Report.

* indicates required

LEAVE A REPLY

Please enter your comment!
Please enter your name here