+40 745 232 788

Online Solutions Development Blog   |  

RSS

Dynamic Jquery Datepicker calendar

posted by ,
Categories: JavaScript
Taggs , , , , , ,

Have you ever wanted to know what do you have to do tomorrow or in the next week without checking your agenda?

Today I’m going to show you how to use JQuery Datepicker and AJAX  to create a calendar that looks like this:

jquery calendar

This dynamic datepicker calendar will allow users to click on a date and see the events. It’s easy to create and very useful. The best part is that only the dates from the calendar that contain events are the clickable ones. Only by watching you will quickly see in what days of the month you have events. Now let’s begin!

To create a jquery calendar we will use a HTML file, a Javascript file and a PHP file requested with AJAX. Let’s begin!

1. The html file

This is the file you’re going to see in the browser. This file is the most important one because it contains the link to the JQuery libraries and the stylesheets.

<!-- stylesheets -->

<!-- js files -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js">// <![CDATA[
    mce:0
// ]]></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js">// <![CDATA[
    mce:1
// ]]></script>

Now that we’ve included the libraries, we have to add the output somewhere in the page. For this we’ll use 2 div elements (remember their ids because you’ll need them in the code). You don’t need to populate them. Just leave them like that.

<!-- this div is used for the dialog box --></pre>
<div id="dialog"></div>
<pre></pre>
<div id="datepicker"></div>
<pre>

2. The javascript file

You can also put this code in the html file between the “<script>” tags. This script will have 2 parts:

  • The first part contains the function that is invoked when the page is loaded:
    $(document).ready(function()
    {
    	var selected_dates = new Array();
    	// gets all the events from the database using AJAX
    	selected_dates = getSelectedDates();
    
    	$('#datepicker').datepicker({
    		dateFormat: 'yy-m-d',
    		inline: true,
    		beforeShowDay: function (date)
    		{
    			// gets the current month, day and year
    			// Attention: the month counting starts from 0 that's why you'll need to +1 to get the month right
    			var mm = date.getMonth() + 1,
    				dd = date.getDate(),
    				yy = date.getFullYear();
    			var dt = yy + "-" + mm + "-" + dd;
    
    			if(typeof selected_dates[dt] != 'undefined')
    			{
    				// puts a special class to the dates in which you have events, so that you could distinguish it from the other ones
    				// the "true" parameter is used to know which are the clickable dates
    				return [true, " my_class"];
    			}
    
    			return [false, ""];
    		},
    		onSelect: function(date)
    		{
    			// puts the event's title in the dialog box
    			$("#dialog").attr("title",selected_dates[date]['event_title']); // for the first time you open the popup
    			$("#dialog").dialog("option","title",selected_dates[date]['event_title']);
    			// puts the event's description text in the dialog box
    			$("#dialog").text(selected_dates[date]['event_description']);
    			// show the dialog box
    			$("#dialog" ).dialog();
            }
    	});
    });
    
  • The second part is the function that returns all the events from the database using AJAX:
    function getSelectedDates()
    {
    	var the_selected_dates = new Array();
        $.ajax(
        {
            url: 'events.php',
            dataType: 'json',
            async: false,
            success: function(data)
            {
    			$.each(data, function(n, val)
                {
                    the_selected_dates[val.event_date] = val;
                });
            }
        });
        return the_selected_dates;
    }
    

This is just an example of what you can obtain in the dialog box. You can also add a date (or anything else). There’s no limit.

3. As you can see in the javascript file, we have a PHP document requested with AJAX. You’ll need a database that has the events which you want to show. This is the code for creating the table that we will use:

CREATE TABLE IF NOT EXISTS `events` (
  `event_id` int(11) NOT NULL auto_increment,
  `event_date` date NOT NULL,
  `event_title` varchar(100) NOT NULL,
  `event_description` text NOT NULL,
  PRIMARY KEY  (`event_id`)
)

In events.php, take all the events and put them in array. Now encode it in a json.
NOTE: I recommend you to customize this function and take only the events from the month/year where you have a large database.

$dates = array();
try
{
	$stmt = $dbh->query('
							SELECT
								*
							FROM
								events
			   			');
}
catch (PDOException $e)
{
	print($e->getMessage());
	die;
}
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
	// because $row['event_date'] will have this form: 2012-01-10 and in Javascript we have 2012-1-10, we need to rewrite it in the way we use it in Javascript, so we could compare it
	$row['event_date'] =  date("Y-n-j", strtotime($row['event_date']));
	$dates[] = $row;
}
echo json_encode($dates);

You can download an archive with the code here.

If you have questions or suggestions please, don’t hesitate to tell me.

If you liked this post
you can buy me a beer

76 Responses to Dynamic Jquery Datepicker calendar

Add a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Also, if you want to display source code you can enclose it between [html] and [/html], [js] and [/js], [php] and [/php] etc