
New Tutorial — Create an AJAX Calendar with PHP
Posted on July 26th, 2008 in AJAX, PHP, Prototype, XHTML
In my newest tutorial, you learn how to quickly render a calendar using PHP's date() and mktime() functions. Then provide some AJAX functionality to move between months without having to reload the page. This tutorial walks you through a great way to build the foundation in PHP for any calendar needs you might have on your site.
Check out my new tutorial, Create an AJAX Calendar with PHP, to learn how to render a calendar with PHP and use AJAX request to move from month to month.

Increasing appendChild Performance with DOM Tricks
Posted on July 22nd, 2008 in DHTML, Firefox, IE7, JavaScript, Optimization, Performance
A recent blog post by John Resig has outlined a performance sensitive method of appending many elements to your document. His suggestion, using DocumentFragment as the container object to which to append all child nodes, is backed by some pretty impressive benchmarks. The most drastic performance improvements by using this method of appending objects to the document are witnessed by Internet Explorer and Safari, IE6 improved by 65%, IE7 by 73% and Safari by 71%.
In looking at his code used to test this, some users argued that his test cases were slightly skewed as the container object was handled in two different manners. In the case using appendChild for each childNode, the container object was looked up on the gathered div array using the loops index to point to the value. Why not store it they asked? This led to accusations that in the case that switches to using the DocumentFragment, the benefit may be derived from the idea that the container object is accessed as a stored value inside the loop. This also lead to questioning that, in his second case, the majority of the content was being appended to an object not yet living in the DOM.
This begs the questions– Does the perceived performance increase being witnessed in this case come from the fact that the container object is detached from the DOM while being appended? I decided to dive in…
The Procedure
To do this, I set up three cases and tested in both Firefox 2 and Internet Explorer 7. Knowing that the original idea, looping through the divs and accessing the container as div[i], was the least desirable, I decided to toss that out the window from the get go.
For my first case, "Appending to Attached Div", I stuck with the structure of John's control case, in which the nodes are appended directly to an element still active in the DOM. The one tweak I did make, was to store a reference to the container div rather than using div[i]. This was as simple as setting var container = div[i] inside the first loop. This resulted in:
var div = document.getElementsByTagName("div");
for ( var i = 0; i < div.length; i++ ) {
var container = div[i];
for ( var e = 0; e < elems.length; e++ ) {
container.appendChild( elems[e].cloneNode(true) );
}
}
Case 2 involved using John's DocumentFragment method verbatim. This presented an element of control to my test in relation to his.
In the 3rd case, I decided to use the method just like in case 2, however rather than using createDocumentFragment() I created a table element with createElement("table"). This was stored as the container to which to append the children elements.
var div = document.getElementsByTagName("div");
var container = document.createElement("table");
for ( var e = 0; e < elems.length; e++ ) {
container.appendChild( elems[e] );
}
for ( var i = 0; i < div.length; i++ ) {
div[i].appendChild( container.cloneNode(true) );
}
My Results
The results are as follow, with time to execute represented (in seconds).
| Appending to Attached Div | Appending to Document Fragment | Appending to Table | |
| FF2 | 2.046 | .430 | .481 |
| IE7 | 4.134 | 3.256 | 3.715 |
In Conclusion
After going through this test, I decided that John was definitely onto something. He found the most optimized way to approach this method. Between the two cases in which I appended the content to an object that was not yet in the DOM (for the elems array), the DocumentFragment method proved to be more efficient by about 10%. The one thing I would like to add–that I feel my test proved–is that when you are doing the majority of your appending, you should be doing it to an object that is not currently contained within the DOM. You can then later append that object to its destination container.
P.S. On a humorous note, the original case that John was using in his test took far too long for me to run with the sheer volume of div's I was trying to populate. In fact, it caused Firefox to prompt me to stop the script and Internet Explorer just locked up… Definitely make sure you use one of these presented solutions for appending nodes to improve your performance!
When working with arrays in PHP, you will encounter times when you need to easily remove known values from that array. There are a couple of quick techniques I use to accomplish this.
The first, uses the PHP function array_diff(). When using array_diff to remove an item from an array, you pass your current array as the first parameter and an array containing only that value you want to remove as the second.
We'll start with our intial array, a list of dog breeds:
$dogs = array('poodle','beagle','great dane','dachshund');
Now, we'll use array_diff to get rid of the poodle to form a list of hounds
$hounds = array_diff($dogs,array('poodle')); // --> array(3) { [1]=> string(6) "beagle" [2]=> string(10) "great dane" [3]=> string(9) "dachshund" }
The second method utilizes the handy array_filter() function for more complex removal. When using array_filter to remove an item from an array, we pass our current array as the first parameter and the filtering callback function as a string as the second parameter.
For this example, we will keep it simple and stick to checking whether or not the type of dog is a poodle. If it is not a poodle, our filtering function will return TRUE and be added to the resulting array.
function gethounds($dog){
if($dog != 'poodle')
return TRUE;
}
$hounds = array_filter($dogs,'gethounds'); // --> array(3) { [1]=> string(6) "beagle" [2]=> string(10) "great dane" [3]=> string(9) "dachshund" }

Select All Checkboxes with Prototype JS
Posted on July 10th, 2008 in DHTML, Forms, JavaScript, Prototype, XHTML
If you are a looking for an easy way to select all checkboxes on a page, there are a number of ways you can quickly accomplish this with the Prototype JS library.
Let's say your HTML looks like this:
<form id="options">
<fieldset><input type="text" value="test"></fieldset>
<fieldset><input type="checkbox" value=0> 0</fieldset>
<fieldset><input type="checkbox" value=1> 1</fieldset>
<fieldset><input type="checkbox" value=2> 2</fieldset>
<fieldset><input type="checkbox" value=3> 3</fieldset>
</form>
It's fairly straight forward to grab all of the input elements of type "checkbox" without also getting the element of type "text".
In both cases we will store our results as objects in an array, named checkboxes.
var checkboxes = [];
Now that we have this array ready for our objects, let's select them.
The first method, uses the $$ operator to select all inputs on the page. Then we use the each() method to iterate through each input element and check the type. If our type is equal to the string 'checkbox', store it to our array checkboxes.
checkboxes = $$('input').each(function(e){ if(e.type == 'checkbox') checkboxes.push(e) });
The second method, uses the hand Form object method called getInputs(). To use this method, first we need to select the form object. In this example, we do so by used the $ operator and the id attribute of the form. Once we have that object, we call the getInputs() method and pass it the argument 'checkbox', which will define the input type we are seeking.
var form = $('options');
checkboxes = form.getInputs('checkbox');
In both of these cases, checkboxes will be equal to:
checkboxes // ---> returns "[input 0, input 1, input 2, input 3]"
If you would like to check all of these checkboxes, you can do so with this line of code:
checkboxes.each(function(e){ e.checked = 0 });
You can also assign it to a link with this HTML:
<a href="#" onclick="checkboxes.each(function(e){ e.checked = 0 });">Select All</a>
PHP dynamic variables have a lot of usefulness. As you're programming for the web, you'll come across many cases where you have a block of code that you will want to use for a number of different cases. This is very common when you have output or validation helpers.
In this quick howto, I will show you how to use PHP's dynamic variables to create a basic little text output helper function. The example is simple, but the ability to do this comes in extremely handy as you start working on bigger projects.
First, let's define two arrays of information, one about my car and one about my favorite guitar:
'Saturn','model'=>'Vue');
$guitardata = array('make'=>'Heritage','model'=>'H-535');
Now that this data is set, we can create a function to put together our text output.
function buildAboutMe($data,$verb){
global ${$data.'data'}; // Bring the array within scope
$info = ${$data.'data'}; // Store the array as $info
return "I $verb a {$info['make']} {$info['model']}.";
}
In this function, we are passing in the $data parameter as a string. The function then uses a dynamic variable to bring the corresponding array within scope of the function. If we pass in 'myinfo', this would be the same as declaring
global $myinfodata
Then we store the $myinfodata array as that same value and access it when putting the string together. Simple enough!
The final code is the actual function calls, passing in a verb argument to make our output make sense based on what we're describing.
$car = buildAboutMe('car','drive');
echo $car; // I drive a Saturn Vue.
$guitar = buildAboutMe('guitar','play');
echo $guitar; // I play a Heritage H-535.
And that's all there is to it! This is a pretty basic example but you can imagine what kind of door using dynamic variables can open as you are writing your next web application!
When providing digital downloads, such as ebooks or mp3s, a common issue is protecting those files from direct downloads and hot linking. If your downloads require purchase, a license to be obtained, or you just want to keep tabs, you can restrict access to these files using Apache's .htaccess configuration files. The control achieved through .htaccess will allow you to set file permissions on a per-directory basis.
The new tutorial, Protect Downloadable Files with .htaccess Rules, walks you through a straightforward method of keeping your digital downloads under your jurisdiction through .htaccess rules.

First Letter of a String in JavaScript: test.CharAt() vs test[]
Posted on April 24th, 2008 in JavaScript
When we use a programming language everyday, now and then we find ourselves stumbling upon intricacies of that language that need some clarification. Today I encountered this as I was using JavaScript to convert an object to an XML string. While working through the object, there was a particular piece of the code that needed to evaluate the first character of a string. For those of you versed in JavaScript, you understand that there are actually a number of ways to accomplish this, most effectively by treating the string like an array [because JavaScript doesn't mind] or by using the handy charAt() function. Both seem to work fine… but what's the difference you might ask?
var test = 'string';
test[0];
// ---> returns "s"
var test = 'string';
test.charAt(0);
// ---> returns "s"
Doesn't seem to be a difference here. I was pretty stumped until my colleague, Nathan, suggested I try an invalid index.
var test = 'string';
test[5];
// ---> returns ""
var test = 'string';
test.charAt(5);
// ---> returns null
A-ha!
As you can see, charAt() returns a string regardless of the argument actually being a valid index or not. This is extremely useful in the case that you need the returned value to be a string for later usage.
Grabbing the value directly from the string as you would do with an array is also a useful technique if you need to know that it is indeed an invalid index.
Also, could one assume that comparing against null performs better than performing a string comparison?
Update: As it turns out, IE does not support the test[] method of accessing the value. It is advised that you always use test.CharAt().
With the release of WordPress v 2.3, there were some structural changes to post categories that broke functionality of version 1.01 of the Ryboe Tag Cloud. I have finally had a chance to sit down and make the couple of quick changes necessary to restore functionality. In this newest version of the Ryboe Tag Cloud, I have also built in backwards compatibility– so if you have not yet upgraded your WordPress install to 2.3, you should still experience a flawless experience.
Without further ado, here is the new plugin.
Download Ryboe Tag Cloud WordPress Plugin
Past Releases:
Release 1.01
Original Release

Saving your Server with WordPress Internal Cache
Posted on July 15th, 2007 in Caching, Optimization, WordPress
Caching is a very important skill for you to obtain when building websites that may receive a lot of traffic at any given time. When using WordPress, you have a very good opportunity to get into some heavy duty caching action so that you can save your server a little bit of work.
The Why.
Just a low level explanation of exactly what happens when your web server displays a page to a visitor. When the visitor comes to your site and page is requested, the WordPress application requests, from your database system, the information that relates to the corresponding post(s). The issue therein lies that normally, every single visitor to your site requires your server to query the database and grab the text to display. As you can imagine, this can quickly get very expensive as far as your server's resources are concerned. This is why caching can really save you. Through caching, your site content will be stored in a "flat file" on your server. This will eliminate the need for your database server to be queried with every single page view.
The How.
To get started, goto your WordPress files and /wp-config.php in your favorite text editor. In this file, you'll see all of the current configuration settings for your database connection.
Add the following line to the end of all that (it really doesn't matter where this code is, as long as it lives in the wp-config.php file):
define('ENABLE_CACHE', true); // cache setting, true means on
Once you've saved that file, go ahead and upload to your server, overwriting the previous file.
Now you have turned on caching! But before you get blogging again, there's one more thing to do.
What we need to do next is create a place for these cached "flat files" to live on your server.
The default location for your cached files is in the directory on your server /wp-content/cache. If that folder is not there, then create it and name it appropriately. Also, you need to double check that the server has permission to write to this directory. In order to do so, you will need to CHMOD the folder to a setting of '777'.
And there you have it! That's how simple it is to use the caching functionality of WordPress.
If you're more technically advanced and would like to learn more about what you can do to your server to speed up your blog, check out this excellent article entitled 4+1 Ways To Speed Up WordPress With Caching
The crew over at WordPress has announced the release of version 2.2. This has been a widely anticipated release, as it is the first to include the ever popular WordPress Widgets pluging built right into the release. This means no more customizing your themes to allow for the plugin!
Also included in the release is full on support for Atom feeds and some core speed optimizations.
I went ahead and got the install fired up on my local dev site and it works like a charm! Compliant with both PHP 4.3 and PHP 5.2. As always, the upgrade is a breeze. Most of all, don't forget to get the Ryboe Tag Cloud Plugin added into your install! (just toss it in the /wp-content/plugins/ directory)
To read more about the release, head over to the official WordPress Development Blog entry
You can download WordPress 2.2 here

