+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

  1. Good afternoon, when I have words with accent he returns null. How do I fix?

    • Hello, Rodrigo. The problem it’s with the json_encode function from the PHP file.
      This is not the object of this blog post. Please research character encoding issues and JSON.

  2. Obrigado, só mais uma duvida quando cadastro alguma palavra com acento ele me retorna nulo.

  3. Hello – amazing codes!! I’ve been searching high and low for this and your codes work beautifully.
    One question – I’m trying to use your calendar for a reservation system. I’d love to be able to update the database to make that event date no longer available once someone selects and then submits it as a form.
    Any advice on how to incorporate this functionality?
    Thank you again -I’ve scoured the world wide web for this and none have been as clean and effective as yours

    • Hello, you can easily do this using AJAX. You already use it to take the available dates so you have an example how to do it. In the dialog you open:

      <div id="dialog"></div>

      you can put a form where you take your dates for a reservation, then submit it, send the dates through AJAX, see if the reservation is valid (insert it in your database for example) and if this operation returns “true”, then instead of

      return [true, " my_class"];

      put

      return [false, " my_class"];

      so the other users can’t select that date anymore. That should do the trick. Hope it helps you!

      • Hello – Thank you for your reply. PHP PDO is new to me….so I’m struggling to incorporate the “GET [‘ID’]” statement into mysql select. More specifically, the calendar needs to only reflect the availability of the venue ID the user has selected in a previous page (and has passed the variable ID on in the form of “…events.php?VenueID = VenueID” ). I have the below code …if I were to write “WHERE VenueID=1″ it works..so I know the code is working, I just don’t know how it can capture the VenueID the previous page has passed on. Can you help? Thank you!

        setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $dbh->setAttribute(PDO::ATTR_PERSISTENT, true);
        $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
        $dbh->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);

        }
        catch (PDOException $e)
        {
        echo ‘Error!: ‘ . $e->getMessage() . ”;

        }

        // take the events from the table named “events”

        try
        {

        $stmt = $dbh->query(‘
        SELECT
        *
        FROM
        venue_room_availability WHERE VenueID=’ .$_GET[“VenueID”]
        );
        }
        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 the way we use it in Javascript so we can compare it
        $row[‘event_date’] = date(“Y-n-j”, strtotime($row[‘event_date’]));
        $dates[] = $row;
        }

        echo json_encode($dates);
        ?>

  4. Sorry let me rewrite the php codes I just posted above more neatly. here it is

    
    <?php
    
    // Initializations of the variables used
    
    $dates = array();
    
    // MYSQL connection credentials
    
    include_once "Connection.php";
    
    
    // PDO - connect to the database
    try 
    {
    	$dbh = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
    
    	$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    	$dbh->setAttribute(PDO::ATTR_PERSISTENT, true);
    	$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
    	$dbh->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
    
    	
    	} 
    catch (PDOException $e) 
    {
    	echo 'Error!: ' . $e->getMessage() . '<br/>';
    
    }
    
    // take the events from the table named "events"
    
    try
    {
    
    	$stmt = $dbh->query('
    							SELECT 
    								*
    							FROM
    								venue_room_availability WHERE VenueID=' .$_GET["VenueID"] 
    						);
    }
    catch (PDOException $e)
    {
    	print($e->getMessage());
    	die;
    }
    //echo mysql_error($dbh);
    
    	
    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 the way we use it in Javascript so we can compare it
    	$row['event_date'] =  date("Y-n-j", strtotime($row['event_date']));
    	$dates[] = $row;
    }	
    
    echo json_encode($dates);
    ?>
    
    
    
    
    • Hello,

      for one thing I don’t think it is the purpose of this blog post to talk about the proper usage of PDO, this discussion turns into something that is more appropriate for a forum and not for a blog.

      about your source code: you are using PDO in an way that is not recommended. If you use the get parameter directly in your query you don’t take advantage of the security provided by the prepared statements.

      you should read about pdo on php.net here: http://php.net/PDO

      the query should be prepared for execution with the prepare method (http://www.php.net/manual/en/pdo.prepare.php)
      you should have a placeholder for the venue id
      after preparing you should bind the parameter with the bindParam method (http://www.php.net/manual/en/pdostatement.bindparam.php and check out http://www.php.net/manual/en/pdostatement.bindvalue.php also)
      and after that you can execute the query with the execute method (http://www.php.net/manual/en/pdostatement.execute.php)

      your current query is prone to sql injections and you are not using pdo in the way it is meant to

      about the value you receive in get we can’t guess what is the problem, you should start debugging as there could be a lot of reasons for this (from mod rewrite to improper usage). print the contents of the $_GET superglobal and see what values are stored

  5. Thanks for sharing your experience. One little thing I did was use jQuery.datapicker.formatDate( format, date, settings ) to simply the handling of dates.

    In your code, you use the following logic to create a date string that can be used in your beforeShowDay event handler:

    // 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;
    

    Using jQuery.datepicker.formatDate, this can be simplied to:

    var dt = jQuery.datepicker.formatDate('yy-mm-dd', date);
    

    Since the formatDate utlity method is aware of javascript date object semantics you don’t have to worry about months being zero-based and having to add zero to them, for example. It can handle the date object as is.

    An additional benefit of this technique is that I can use the ‘yy-mm-dd’ date format when configure the datepicker (dateFormat: ‘yy-mm-dd’) and I can use this same date format on the server when returning a list selectable dates.

    Thanks again for your post and I hope you find this additional information useful.

  6. how to display selected date from database red or another color?

    • I’m not sure what exactly you want to do, but you give a class to the selected dates (see the code and you’ll see I add a class named “my_class”). Play with that in CSS…

  7. hi,
    i have been playing arround with this code.
    But in the example that i have downloaded the event_title is not updating when selecting a different date in the calendar.
    So it pulls the title from the first event that you select but it stays the same when you select a different date.

    Any suggestions?

    • Hello, yes, you are right. It’s a mistake I’ve done. I have to put

      $('#dialog').dialog( "option" , 'title' , selected_dates[date]['event_title']);
      

      I’ve updated the post.
      Thank you for pointing this out and, probably, making life of others easier!

  8. Hello Andreea,
    This is awesome blog i really like it i have a question that when i load the date picker it returns date disable mode if i click the next or previous button then display current events highlighted.

    i want the date picker to load current date highlighted and show the rest of events by document.ready

    please help me thanks in advance

  9. Hello,

    Is there a way to include a link from the popo up to a page?
    For exemple, when you click on the title of the dialog box, you go to index.php ?

    Thank you very much for you answer and for your script

  10. i want to add couple to fields like event_venue, client_name… i did this, but how to display in dialog box? i m not able to show all fields.

    • Hi, Deepak. It’s easy. Instead of

      $("#dialog").text(selected_dates[date]['event_description']);
      

      Put this:

      $("#dialog").html("<p>" + selected_dates[date]['event_description'] + "</p>" + "<p>" + selected_dates[date]['event_venue'] + "</p>");
      

      I used $(“#dialog”).html instead of $(“#dialog”).text so I could use html tags to separate every field. This should do the trick.

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