+40 745 232 788

Online Solutions Development Blog   |  


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[
// ]]></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js">// <![CDATA[
// ]]></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>
<div id="datepicker"></div>

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:
    	var selected_dates = new Array();
    	// gets all the events from the database using AJAX
    	selected_dates = getSelectedDates();
    		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
    			// puts the event's description text in the dialog box
    			// 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();
            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:

  `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();
	$stmt = $dbh->query('
catch (PDOException $e)
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

  1. Thank you for a terrific Tutorial, much appreciated!
    I would like to know how an Event Date could be accessed via an Array instead of a JSON PHP file.

    • Hello, Roland.

      The PHP file just sends an array of objects that have fields like event_title, event_description or event_date. All you need to do is to get a similar array from another source. For that you can change the function getSelectedDates to use the data you need.

      Also you can change the logic where you find the selected_dates variable used and apply your on custom structure.

      I hope this helps and thank you for your appreciation.

  2. Thank you for your Tutorial, i use it same Time and it work fine.
    Now i use php 5.5 and its dosent work.
    Any idea what going wrong. Sorry for my bad englisch.

    • Hello, Frank.
      I can’t know what your problem might be just by what you said. So I have a few questions:

      1. Are you sure that you used the samples showed in this tutorial?
      2. Did you try to debug your script(s)? If so you must have seen an error message somewhere. What was it?
      3. What’s your full version number for the current and maybe previous setup? You can check the PHP change log to see if the upgrade affected you in any way.
      4. The PHP part of this tutorial is pretty basic, are you sure that this is what is causing your problem and not some other code your wrote?
  3. Hello, thanks for the information you provided. i found this tutorial extremely useful and it has ignited my passion to learn programming.

    I downloaded the archive with code, but it did not help me solve my immediate need. Please is there a way you can help me to download a complete source file.
    The one i downloaded, i am unable configure all the requirements and details. i created the database, and ran the html file, and nothing showed up in the browser.

    Thanks for your assstance.

    Great day.

    • Hello, Leo.
      What have you tried to find the issue? Can you tell me what kind of error it is? Is it something about the JavaScript (do you see any message in the console) or is it in PHP?

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