AJAX calendar

Small, short code snippets that other people may find useful. Do you have a good regex that you would like to share? Share it! Even better, the code can be commented on, and improved.

Moderator: General Moderators

User avatar
findarato
Forum Newbie
Posts: 2
Joined: Thu Dec 21, 2006 10:15 am

Post by findarato »

Very nice calendar, I am even considering using it =)
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

I ran the code and it threw up tons of warnings (PHP5) so I added a few little fixes (identified with an "//arborint" comment) that fix those problems. I also added Moogle's changes. Here's the code:

Code: Select all

<?php
//Released under the GPL license


//--------------------
// CONFIG

//set the styles of the calendar
$styles['current']['day'] = array(array('js'=>'backgroundColor',
                                        'css'=>'background-color',
                                        'mouseovervalue'=>'#FFFFFF',
                                        'value'=>'#d7e9ff'));
$styles['current']['weekend'] = array(array('js'=>'backgroundColor',
                                            'css'=>'background-color',
                                            'mouseovervalue'=>'#FFFFFF',
                                            'value'=>'#a7cbf5'));
$styles['other']['day'] = array(array('js'=>'backgroundColor',
                                      'css'=>'background-color',
                                      'mouseovervalue'=>'#FFFFFF',
                                      'value'=>'#afc3d9'));
$styles['other']['weekend'] = array(array('js'=>'backgroundColor',
                                          'css'=>'background-color',
                                          'mouseovervalue'=>'#FFFFFF',
                                          'value'=>'#d9e0e7'));
$styles['nav'] = array(array('js'=>'backgroundColor',
                             'css'=>'background-color',
                             'mouseovervalue'=>'#FFFFFF',
                             'value'=>'#5995de'),
                       array('js'=>'color',
                             'css'=>'color',
                             'mouseovervalue'=>'#333333',
                             'value'=>'#FFFFFF'),
                       array('js'=>'display',
                             'css'=>'display',
                             'mouseovervalue'=>'block',
                             'value'=>'block'),
                       array('js'=>'textDecoration',
                             'css'=>'text-decoration',
                             'mouseovervalue'=>'none',
                             'value'=>'none'));
$styles['table'] = '';		//arborint change 2006-12-21
$styles['th'] = 'background-color:#5995de;color:#fff;font-weight:bold;';
$styles['date'] = 'text-align:center;';
$styles['td'] = 'text-align:center;';
$styles['a'] = 'display:block;height:100%;text-decoration:none;padding:3px;';


//set the date format to return - use PHP's date() syntax
$date_format = 'd/m/Y';



// /CONFIG
// You shouldn't need to go beyond this point
//--------------------


if(isset($_POST['mode']) && ($_POST['mode'] == 'PHP'))
{
  actAsPHP($styles,$date_format);
}
else
{
  actAsJavascript();
}



function actAsPHP($styles,$date_format)
{
  $id = $_POST['id'];

  if(isset($_POST['curr_stamp']))
  {
        if (isset($_POST['direction'])) {
            $direction = ($_POST['direction'] == 'subtract') ? '-' : '+';
        $now = strtotime($direction.'1 month',$_POST['curr_stamp']);
        } else {
                $now = $_POST['curr_stamp'];
        }
  }
  else
  {
    $now = time();
  }
  
  $first_of_month = mktime(0,0,0,date('m',$now),1,date('Y',$now));

 //-------------------
 //build the day array

 //get the Monday of the week that has the 1st of the month
 $first_day_stamp = $first_of_month;
 while(date('w',$first_day_stamp) > 0)
 {
   $first_day_stamp = strtotime('-1 day',$first_day_stamp);
 }

 //insert all days from last month
 $curr_stamp = $first_day_stamp;
 while($curr_stamp < $first_of_month)
 {
   $days[1][] = $curr_stamp;
   $curr_stamp = strtotime('+1 day',$curr_stamp);
 }

 //insert all days from this month
 $week = 1;
 while(date('n',$curr_stamp) == date('n',$first_of_month))
 {
   $days[$week][] = $curr_stamp;
   $week = (date('w',$curr_stamp)) == 6 ? $week + 1 : $week;
   $curr_stamp = strtotime('+1 day',$curr_stamp);
 }

 //insert all the days from next month
 while(date('w',$curr_stamp) > 0)
 {
   $days[$week][] = $curr_stamp;
   $curr_stamp = strtotime('+1 day',$curr_stamp);
 }

 //-----------------
 //display the table

 //open the table & display the navigation

 $style = '';			//arborint change 2006-12-21
 $mouseOver = '';		//arborint change 2006-12-21
 $mouseOut = '';		//arborint change 2006-12-21
 foreach($styles['nav'] as $property)
 {
   $style .= $property['css'].':'.$property['value'].';';
   $mouseOver .= 'this.style.'.$property['js']."='".$property['mouseovervalue']."';";
   $mouseOut .= 'this.style.'.$property['js']."='".$property['value']."';";
 }

 $monthyear = date('M \'y',$first_of_month);
 echo <<<TABLE
        <table cellspacing = '1' style = '$styles[table]'>
          <tr>
            <th style = '$styles[th]' colspan = '2'>
              <a href = "javascript:void(0);" style = "$style" onmouseover = "$mouseOver" onmouseout = "$mouseOut" onClick = "loadDate('$id','$first_of_month','subtract');">
                &laquo;
              </a>
            </th>
            <th colspan = '3' style = '$styles[th] $styles[date]'>
              $monthyear
            </th>
            <th style = '$styles[th]' colspan = '2'>
              <a href = "javascript:void(0);" style = "$style" onmouseover = "$mouseOver" onmouseout = "$mouseOut" onClick = "loadDate('$id','$first_of_month','add');">
                &raquo;
              </a>
            </th>
          </tr>
TABLE;
 


 foreach($days as $week)
 {
   echo '<tr>';
   foreach($week as $day)
   {
     //setup how the day should look
     if(date('n',$day) != date('n',$first_of_month))
       if(date('w',$day) == 0 || date('w',$day) == 6)
         $style_properties = $styles['other']['weekend'];
       else
         $style_properties = $styles['other']['day'];
     else
       if(date('w',$day) == 0 || date('w',$day) == 6)
         $style_properties = $styles['current']['weekend'];
       else
         $style_properties = $styles['current']['day'];

#     unset($style);		//arborint change 2006-12-21
#     unset($mouseOver);	//arborint change 2006-12-21
#     unset($mouseOut);		//arborint change 2006-12-21

	 $style = '';			//arborint change 2006-12-21
	 $mouseOver = '';		//arborint change 2006-12-21
	 $mouseOut = '';		//arborint change 2006-12-21
     foreach($style_properties as $property)
     {
       $style .= $property['css'].':'.$property['value'].';';
       $mouseOver .= 'this.style.'.$property['js']." = '".$property['mouseovervalue']."';";
       $mouseOut .= 'this.style.'.$property['js']." = '".$property['value']."';";
     }

     $day_of_month = date('j',$day);
     $click_val = date($date_format,$day);
     echo <<<CELL
            <td style = '$styles[td]'>
              <a href = "javascript:void(0);"
                 style = '$styles[a] $style'
                 onMouseOver = "$mouseOver"
                 onMouseOut = "$mouseOut"
                 onClick = "document.getElementById('$id').value = '$click_val';document.getElementById('$id').style.display = 'block';document.getElementById('$id').focus();divNode = document.getElementById('calendar');divNode.parentNode.removeChild(divNode);">$day_of_month
</a>
            </td>
CELL;
   }
   echo '</tr>';
 }
 echo '</table>';
}//function: actAsPHP()

function actAsJavascript()
{
  $uri = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
  header('Content-type: text/javascript;');
 
  echo <<<JAVASCRIPT
    function loadDate(pFieldID)
    {
      try
      {
        if(window.XMLHttpRequest)
        {
          reqsend = new XMLHttpRequest();
        }
        else
        {
          reqsend = new ActiveXObject("Microsoft.XMLHTTP");
        }
      }
      catch(e)
      {
        alert('Your browser does not support XMLHTTP.');
      }

      try
      {
        reqsend.open("POST",'$uri');
        reqsend.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

        post = "mode=PHP&id=" + pFieldID;

        //'arguments' is a JS construct that represents
        //all the arguments sent to a function
        if(arguments[1])
        {
          post = post + '&curr_stamp=' + arguments[1];
                  
                  if (arguments[2]) {
                        post = post + '&direction=' + arguments[2];
                  }
        }
        reqsend.setRequestHeader("Content-Length",post.length);
        reqsend.send(post);
        reqsend.onreadystatechange = function()
        {
          if(reqsend.readyState == 4 && reqsend.status == 200)
          {
            var responseText = reqsend.responseText;

            //create the new div
            //it's not inserted into the document yet
            calendarDiv = document.createElement('div');
            calendarDiv.setAttribute('id','calendar');

            //remove the div if it exists
            //this avoids duplication of the calendar in the document
            if(document.getElementById('calendar'))
            {
              calendarDiv = document.getElementById('calendar');
              calendarDiv.parentNode.removeChild(calendarDiv);
            }
 
            //insert the new div into the document
            pField = document.getElementById(pFieldID);
            pField.parentNode.appendChild(calendarDiv);

            //hide the text field it's replacing
            document.getElementById(pFieldID).style.display = 'none';

            //fill the new div
            document.getElementById('calendar').innerHTML = responseText;
          }
        };
      }
      catch(e)
      {
        alert(e);
      }
    }
JAVASCRIPT;
}
(#10850)
Li0rE
Forum Commoner
Posts: 41
Joined: Wed Jun 07, 2006 6:26 am

Post by Li0rE »

I made a script that does the same exact thing, except it's 4kb. Would you guys like me to share it here? I don't want to hijack the thread but I don't think I should submit a new code snippet if another one does the same thing.

here is an example: http://shah.lir.dk:2/libcal/ajaxcal.php
Last edited by Li0rE on Sun Feb 18, 2007 12:03 pm, edited 1 time in total.
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post by Kieran Huggins »

cool calendar!

For just a simple JS date picker, there's also http://kelvinluck.com/assets/jquery/datePicker/
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post by pickle »

Li0rE wrote:I made a script that does the same exact thing, except it's 4kb. Would you guys like me to share it here? I don't want to hijack the thread but I don't think I should submit a new code snippet if another one does the same thing.

here is an example: http://shah.lir.dk:2/libcal/ajaxcal.php
Feel free to make a new thread. That way we can each have our own particular feedback.
Nice job by the way.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Locky
Forum Newbie
Posts: 8
Joined: Thu Mar 22, 2007 7:28 pm

Post by Locky »

very nice script however 1 thing i thikn would be a great addition, invalid dates can not be clicked on
User avatar
webgroundz
Forum Commoner
Posts: 58
Joined: Thu Jun 21, 2007 1:20 am
Location: Philippines

Post by webgroundz »

it does not work on FF 2.0, but it works on IE 7

you've done a great job... :P :P :P
Post Reply