:: Archive for the 'Web Development' Category ::

Creating an Accordian Widget Class with Prototype

Posted on August 30th, 2006 in Web Development by Greg

Overview

The following is an example of a simple reusable widget created using the Prototype JavaScript library. The widget is an ‘accordian’ – a widget composed of multiple sections, of which only one is open at a time. This type of widget is available in all sorts of applications, from Microsoft Outlook (circa Outlook 2000), to web applications, and more. In addition to showing off this simple widget, I’d like to walk through it to explain how it works and how to write something like this with Prototype. For all of Prototype’s greatness, there is certainly a lack of documentation that makes it a little bit difficult to get into.

Example

Take a look at the example page I put together showing a few examples of accordians and their capabilities. This article will explain how to put together the class that does this.

Explaination: Creating Reusable Classes

I’ll skip with going through the HTML – you can see that on the example page if you’re interested – it would be helpful in understanding the javaScript here. In this example I’ve used version 1.5.0_rc0 of Prototype. The first line of the accordian.js file has the following:

1
Accordian = Class.create();

Prototype’s Class.create() sets up Accordian as an object that can be instantiated. When the object is instantiated the ‘initialize’ method, its constructor, will be automatically called. You setup all of the methods within the object by defining its prototype – an object with properties and methods. This could be done in the following way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Accordian.prototype = {
	initialize: function(args) {
		// do something
	},
	sectionClicked: function(args) {
 
	},
	openSection: function(args) {
 
	},
	closeExistingSection: function(args) {
 
	}
}

This object could be instantiated in the following way:

1
var myAccordian = new Accordian(options);

Explanation: Writing the Constructor

The constructor needs to take two arguments – the ID of the element that contains the accordian and the type of entry that is used for the header of each section. The constructors main job is getting a list of all of the sections within the accordian and adds onClick event handlers to the headers so that clicking them will open the section. The constructor is shown below:

1
2
3
4
5
6
7
initialize: function(elem, clickableEntity) {
   this.container = $(elem);
   var headers = $$('#' + elem + ' .section ' + clickableEntity);
   headers.each(function(header) {
       Event.observe(header,'click',this.sectionClicked.bindAsEventListener(this));
   }.bind(this));
}

Now to explain what’s going on in the constructor:

  • The first line defines the function that expects two variables – the ID of the element that holds the accordian and the type of element that will serve as the header for a section.
  • The second line sets a class property, ‘container’, to the element passed in with variable ‘elem’. It uses Prototype’s $() function, which in this case is equivalent to document.getElementById()
  • The third line uses the very powerful $$() function that returns an array of all elements that match a given css query. In this case, the query might look like ‘#myAccordian .section h3’, which would return all h3 elements under an element with class ‘section’ under the element with ID ‘myAccordian’.
  • Lines 4-6 setup the event handlers that will be used when the user clicks the headers. This uses the each() function that Prototype adds to arrays in order to quickly loop through an array without using a for loop or creating a bunch of temporary variables. This function takes a function as an argument that will be applied as an iterator over the array. This use of this technique is similar to the foreach concept in PHP (foreach($headers as $header)) and other languages. Because functions are objects in JavaScript, we need to add a trick at the end of the each function defined within ‘each’ – we need to add ‘bind(this)’. This means that within the new function, the ‘this’ keyword will be bound to the Accordian object, not to the function itself.
  • Line 5 uses Prototype’s Event class to setup the observer – in this case it will bind the classes sectionClicked method to any click on the header elements. Similar to the binding needed on the function, the reference to the sectionClicked function is follwed by ‘bindAsEventListener(this)’, which means that inside the event handler, ‘this’ will refer to the Accordian object, not to the clicked header element.

Explanation: Writing the Event Handler

The function referenced as the event handler in the constructor is shown below:

1
2
3
  sectionClicked: function(event) {
   this.openSection(Event.element(event).parentNode);
}

Functions called as an event always get passed an event object. This function takes this event and uses the Prototype ‘Event’ class to get a handle on the parent node of the element that was clicked, the section itself. It then passes this as an argument to another method in this class – openSection.

Explanation: Opening a Section

This function if fairly straightfoward – it checks to see if the section being opened is already open, and if not, calls a function to close the open section, and finally opens the new section. It is shown below:

1
2
3
4
5
6
7
8
9
openSection: function(section) {
	var section = $(section);
	if(section.id != this.currentSection) {
		this.closeExistingSection();
		this.currentSection = section.id;
		var contents = document.getElementsByClassName('contents',section);
		contents[0].show();
	}
}
  • The function takes one argument, the section that is to be opened
  • The second line uses the $() function to get the DOM element. It is important to note that this function can either take the section ID as an argument or the actual section DOM node. The $() function adds this extra flexibility
  • The third line checks to see whether the ID of the section is the same as the currently open section. If it is, no other logic is performed. If it isn’t, the next few lines will open that section.
  • After line 4 calls a function to close the existing section, line 5 sets a class property ‘currentSection’ to the new section
  • Line 6 uses Prototype’s getElementsByClassName, passing the class (contents) and the element under which it should look (the new section). This returns an array of elements
  • Line 7 takes the first element with class contents (their should only be one), and uses Prototype’s show() function to show the element

Explanation: Closing a Section

This last function is the simplest of all – it checks to see whether there is an open section, and if so, it hides it.

1
2
3
4
5
6
closeExistingSection: function() {
	if(this.currentSection) {
		var contents = document.getElementsByClassName('contents',this.currentSection);
		contents[0].hide();
	}
}
  • The second line checks if the currentSection exists – it is only set after the first section has been opened
  • The third line uses the same technique as in the previous function – it uses getElementsByClassName to get the elements with class ‘section’
  • Finally, the hide function will hide this element so that the section is collapsed

The Final Script

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Accordian = Class.create();
Accordian.prototype = {
	initialize: function(elem, clickableEntity) {
		this.container = $(elem);
		var headers = $$('#' + elem + ' .section ' + clickableEntity);
		headers.each(function(header) {
			Event.observe(header,'click',this.sectionClicked.bindAsEventListener(this));
		}.bind(this));
	},
	sectionClicked: function(event) {
		this.openSection(Event.element(event).parentNode);
	},
	openSection: function(section) {
		var section = $(section);
		if(section.id != this.currentSection) {
			this.closeExistingSection();
			this.currentSection = section.id;
			var contents = document.getElementsByClassName('contents',section);
			contents[0].show();
		}
	},
	closeExistingSection: function() {
		if(this.currentSection) {
			var contents = document.getElementsByClassName('contents',this.currentSection);
			contents[0].hide();
		}
	}
}

Conclusion

Though this is a fairly simple example, I hope it helped to explain some of the features of the Prototype library and can get people kickstarted to writing classes with JavaScript. Most of it is very simple…if only there were some real documentation. The best source right now is probably Developer notes for prototype.js, which covers features up to Prototype 1.4. Another site with a compilation of links is http://www.prototypedoc.com/.

Go forth and rid the world of nasty IE5 style, unreadable, browser-sniffing, hackish, global-scope JavaScript!


Ajax Form Validation

Posted on July 30th, 2006 in PHP, Web Development by Greg

Recently I put together a reusable Ajax form validation component that I’d like to share. It is a JavaScript object that collects the values of all of the elements in a form, sends it for processing to the server, and displays any errors. If there are no errors it submits the form. There are several benefits to this approach

  • Allows you to perform complex validation, such as verifying the uniqueness of a username, or checking something in the database…all without reloading the page
  • Allows you to use the same validation routine for both client-side validation and server-side validation
  • Reduces the amount of client-side code needed for validation

The JavaScript used in my example requires the Prototype library. My example uses PHP to perform the validation – more specifically, I’ve used several components of the Zend Framework (PHP5 only). The example uses:

  • Zend_Controller_* classes including the new RewriteRouter to handle the routing within the application
  • Zend_View to handle the output
  • Zend_View_Helper_* classes to build form elements
  • Zend_Config to read in configuration options
  • Zend_Filter to perform several field validations
  • Zend_Json to serialize PHP variables/objects to JSON objects

Did I need all of this stuff on the server-side to put together a simple form validation example? Heck no, but when I’m experimenting with new stuff I like to use a lot of new components so I can learn more about them and be prepared for when I actually do need to use all of this fire power. I’ve been following the Zend Framework carefully, so I wanted to use some of the stuff I hadn’t used yet – particularly the controller architecture.

The HTML and JavaScript

Ok, back to how this JavaScript is used. It’s actually really quite simple. First, you need to include the JavaScript files for both Prototype and AjaxFormValidator in the head of your HTML document:

1
2
<script src="/ajaxValidate/static/js/prototype.js"></script>
<script src="/ajaxValidate/static/js/ajaxFormValidate.js"></script>

Next, you add an ‘onSubmit’ handler to the form you’d like to validate – in this case, mine looks like this:

1
<form action="/ajaxValidate/index/success" method="POST" onSubmit="return submitForm(this);">

The form action is set to the page I’d like the script to go to if the validation is successful. The onSubmit calls a custom function that we still need to define. It passes ‘this’ as an argument – the ‘this’ refers to the form element itself.

Now we define the submitForm() function that the onSubmit of the form will call – it looks like the following:

1
2
3
4
5
6
function submitForm(form) {
	validator = new AjaxFormValidator(form,"/ajaxValidate/index/validate");
	validator.errorDisplay = 'inline';
	validator.inlineElem = 'errorDiv';
	return validator.validate();
}

This function first creates a new AjaxFormValidator object, passing it the form element (or the form id) and the url the validation request should be sent to. The next two lines setup the type of error display that should happen. The following error display types are supported:

  • alert: The default option. Displays all errors in a JavaScript alert box.
  • inline: Displays errors within an element that is defined on the page. You need to set the element name with validator.inlineElem. In this example, errors will be shown in a div with id=”errorDiv”.
  • none: errors won’t be shown to the user. The will be available as an array of errors in the errors property of the validator (i.e. validator.errors). If there are no errors the property will be set to false. Once you have the errors you can perform more advanced error handling/display to the user.

Lastly, validator.validate() will send the values in the form, in an HTTP POST, to the validation url you’ve provided (/ajaxValidate/index/validate in this case). If there are no errors the form will be submitted, if there are errors the will be shown (or not shown if you’ve chosen ‘none’ as the errorDisplay).

The PHP

Once the request is sent it will eventually arrive at the server for processing – in this case, through the magic of routing, it is going to end up in my IndexController in the validateAction method. This function is shown below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public function validateAction() {
	$errors = $this->getErrors($_POST);
	if(count($errors) == 0) $errors = false;
	echo Zend_Json::encode($errors);
}
</php>
This function calls another method within the IndexController class called getErrors, passing in the entire array of POST arguments (values in the form).  It receives back an array full of error strings.  If there are no errors, it changes the value of the $error variable to false.  Lastly, it uses Zend_Json to convert the PHP array/Boolean into the equivalent JavaScript array/Boolean.  This string is printed and sent back to the client.
 
The getErrors function itself is very straightforward - it just does a couple validations and returns back an array of the errors.
<pre lang="php" line="1">
protected function getErrors($values) {
	$errors = array();
	if(!Zend_Filter::isRegex($values['fname'],'/^[a-z]+[a-z 0-9-_]*$/i')) {
		$errors[] = 'First Name is required and may only contain letters, numbers, and spaces';
	}
	if(!Zend_Filter::isRegex($values['lname'],'/^[a-z]+[a-z 0-9-_]*$/i')) {
		$errors[] = 'Last Name is required and may only contain letters, numbers, and spaces';
	}
	if(!Zend_Filter::isRegex($values['email'],'/^[_a-zA-Z-]+[._a-zA-Z0-9-]+@[a-zA-Z0-9-]+\.[.a-zA-Z0-9]+$/')) {
		$errors[] = 'Email is required and must be a valid email address';
	}
	if(!Zend_Filter::isAlnum($values['password']) || (strlen($values['password']) < 6) || (strlen($values['password']) > 12)) {
		$errors[] = 'Password must consist of only letters and numbers and must be between 6 and 12 characters';
	}
	return $errors;
}

Check it out, in action. And that’s about it – pretty simple, huh?

You can download:

Experimenting with Google Checkout and PHP

Posted on July 1st, 2006 in PHP, Technology, Web Development by Greg

Having put together a couple websites (Redstone Studios and Althea) that integrate with Paypal for providing checkout capabilities, I was very interested to look at Google Checkout when it was released this past week. My experience with the Paypal integration was not so good – while I eventually got it to work, it took a ton of experimentation, searching for documentation, and guessing why things weren’t working (i.e. no meaningful error messages). Luckily, Google Checkout doesn’t seem to suffer from these problems – I had it up and running in no time and it seems very solid for what it does. What does it do? Well, it’s basically a checkout system where you can pass in a cart, users can pay by credit card, and then the money gets deposited in your bank account. Google charges 2% of the transaction amount plus twenty cents. The two percent covers the percent Google has to pay the credit card companies, and the twenty cents is some extra cash for Google. If you use Google Adwords, you get a free credit on Google Checkout – for every 1 dollar spent on Adwords you get 10 dollars of sales with no costs.

Google provides sample PHP code for getting the integration going, but unfortunately the code is PHP4 only, and it is ugly ugly ugly code. I decided to put together a simple class that allows simple integration with Google Checkout. The class is PHP5 only because it uses PHP5’s DOM extension.

To use Google Checkout you need to create a Google Checkout account. From there, you can get your merchant id and merchant key, both of which are needed to communicate with Google Checkout. The Google Checkout API works by POSTING XML over HTTP. While Google’s API is very flexible, I’ve chosen to implement a subset that I think would be useful for many people. Also, I’ve only implemented this class to support the creation of the cart and submission to Google, I haven’t included any functionality for greater integration. This greater integration would involve creating web services that Google could call to update the website on changes to the order status, shipping, etc. The way I’ve set this up, all of that is skipped, and store owner would receive orders via email or Google’s Checkout interface.

Limitations:

  • No support for cart expiration
  • No support for merchant calculations for tax/shipping/gift certificates as these require HTTPS and I don’t have it and don’t care to use it
  • No support for requesting the buyers phone number because I didn’t notice that field until just now!
  • No support for shipping restrictions – i.e. shipping option 1 is only available in these zip codes/states/etc
  • No support for complicated tax rules. Tax can be setup on a state by state basis. One alternative tax rule ‘taxfree’ is setup to allow certain items to be tax free. No support for other alternative tax rules.
  • Currently doesn’t support customization of the form and checkout image

In order to work around some of these limitations, I’ve provided a method called setDefaultXML which allows the developer to specify a default XML file to be used. The class will then fill in the items, do the encryption, and generate the form and checkout image. This allows much greater flexibility and support for all of Google’s options, when needed.

Here’s a simple example of how I might use it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
require('GoogleCheckout.php');
 
$merchant_id = 'XXXXXXXXXXXXXXX';
$merchant_key = 'XXXXXXXXXXXXXXXXXXXXXX';
 
$google = new Gregphoto_Service_Google_Checkout($merchant_id,$merchant_key);
$google->setMode('sandbox');
$google->addItem('Doolittle','Doolitle CD by The Pixies (1989)','11.98',1);
$google->addItem('PSCREEN18','18 inch Pizza Screen','7.99',3);
$google->addItem('MYWIDGET01','New tax free widget - Student Use Only','149.21',1,'','taxfree');
$google->addItem('NDISC01','New Customer Discount','-10',1);
$google->editCartUrl = 'http://www.gregphoto.net/index.php?action=editcart&source=google';
$google->continueShoppingUrl = 'http://www.gregphoto.net';
$google->setShipping('UPS Ground',19.99);
$google->setShipping('UPS Next Day',27.99);
$google->setShipping('Instore Pickup',4.99,'pickup');
$google->setStateTax('CA',.0875);
$google->setStateTax('IL',.0525);
 
echo $google->getHTMLForm();
$google->printXML();

Now, for what’s going on:

  • Line 1 includes the class
  • Lines 3 and 4 setup variables for the merchant id and merchant key
  • Line 6 instantiates the class, passing in the merchant id and key
  • Line 7 sets the class to use the Google Checkout Sandbox – this is a testing sandbox where you can setup fake accounts to use while creating your site. Paypal offerers a much richer sandbox functionality.
  • Lines 8-11 add new line items to the cart, setting there name, description, price, quantity, notes, and special tax rules
  • Lines 12 and 13 setup the URLs the user should be sent to if the choose to edit the cart or continue shopping
  • Lines 14-16 setup various shipping options including their prices
  • Lines 17 and 18 setup taxes for the users in specific states. Google Checkout supports much richer rules around taxation, but I kept it simple on a state-by-state level.
  • Line 20 outputs the HTML form and checkout image that will send the cart to Google Checkout and bring the user to the Google Checkout page
  • Line 21 shows the XML cart, for debugging purposes

View this example running on my site
View the API of Gregphoto_Service_Google_Checkout
Download the class and API docs
View Google’s Develper Guide for Google Checkout

Akismet and the Zend Framework

Posted on June 11th, 2006 in PHP, Web Development by Greg

Inspired by Akismet is my Hero on blog.phpdeveloper.org and by the fact that Akismet has already stopped several thousand spam comments on my own WordPress blog, I decided to put together an Akismet class using the Zend Framework (resulting in this being PHP 5 only). For those of you who don’t know, Akismet is a web service that you can send comments to and they’ll let you know whether or not they think it’s spam. It does a great job of spotting spam and was a great addition to WordPress.

This class, which you can download along with api docs uses the Zend Framework’s Zend_Http_Client functionality to perform HTTP posts to Akismet and get the responses back. More specifically, it uses the version of Zend_Http_Client that’s currently in the incubator, not the one in the regular library.

Here’s a simple usage example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$api_key = 'your api key here';
$website_front_page = 'http://www.gregphoto.net';
$message = array(
	'comment_author' => 'viagra-test-123',
	'comment_author_email' => 'viagra-test-123@hotmails.com',
	'comment_author_url' => 'http://www.viagra-test-123.com/ilovespam/',
	'comment_content' => "Please buy my spam.  Mechanically separated meat tastes great!"
);
 
$akismet = new Gregphoto_Service_Akismet($api_key,$website_front_page);
if($akismet->checkIsSpam($message)) {
	echo 'it is spam!';
} else {
	echo 'it is not spam!!';
}

In addition to checking whether a message is spam (Gregphoto_Service_Akismet::checkIsSpam), the following methods are provided, covering the entirety of the Akismet API:

  • Gregphoto_Service_Akismet::validateKey – checks whether or not your api key is valid
  • Gregphoto_Service_Akismet::submitSpam – submits a message to Akismet telling it that it is spam (normally a message that Akismet identified as not being spam)
  • Gregphoto_Service_Akismet::submitHam – tell Akismet that a message it identified as spam is not actually spam

To get an API key for yourself, follow the instructions printed on blog.phpdeveloper.org:

You’ll need to go signup over on WordPress.com and, once logged in, go to your “My Dashboard” (top left link), go to the “Users” tab at the top and right there at the top of the page you’ll see “Your WordPress.com API key is…”. Easy as pie.

Signup for a free blog, but don’t worry…you only need to sign up in order to get a key – you don’t actually have to use the wordpress.com account for anything else…

For anyone looking to build a site or application using the Zend Framework that accepts comments – this could be a good little tool that should integrate very cleanly.

Enjoy, and let me know what you think.

Updated Scriplaculous Sortable Demo

Posted on May 30th, 2006 in Web Development by Greg

I’ve updated the Scriptaculous demo that I put up a while back. You can see it here. There were a large number of comments on the initial post, many of them wondering why the example didn’t work in Scriptaculous 1.6.X. I took a look at it today and after some experimentation made the following changes to get it to work:

  • Reversed the order of creating the sortables – for whatever reason, it seems that the outer most sortable must now be created last, whereas it worked fine when created first before
  • Removed the code to ‘destroy’ the sortables before recreating them – this was necessary before, but it seems that they are automatically destroyed now when creating a sortable on the same element. While this slimmed down the code, it wasn’t essential to get it to work Scratch that. I noticed a bug where dropping elements on the sections wasn’t working if a new group had been created before any of the line items had been added to a group. Adding back the destruction of the line item sortables did the trick. It still seems to be working without the destruction of the page-level sortable though.
  • Added a prefix to the new section id for consistency sake (as per John’s comment)
  • Other miscellaneous JavaScript and CSS cleanup

There were also several comments questioning whether this positioning can be saved to the database. That’s exactly what the debug function is aimed at doing – showing the user how to get at the positioning information with JavaScript. Once you’ve got it into a JavaScript string/array/object, it’s trivial to put it into an input and submit a form.

Enjoy.

Greg