Ask Ben: Building An AJAX, jQuery, And ColdFusion Powered Application

// Create a Javascript class to handle the contact form.
function ContactForm(){
	var objSelf = this;
 
	// Get a jQuery reference to the form.
	this.Form = $( "#contact-form" );
 
	// Get jQuery references to the key fields in our contact
	// form. This way, we don't have to keep looking them up.
	// This will make it faster.
	this.DOMReferences = {
		Name: this.Form.find( "input[ name = 'name' ]" ),
		Hair: this.Form.find( "input[ name = 'hair' ]" )
		};
 
	// Bind the submission event on the form.
	this.Form.submit(
		function( objEvent ){
			// Submit the form via AJAX.
			objSelf.SubmitForm();
 
			// Cancel default event.
			return( false );
		}
		);
}
 
 
// Define a method to help display any errors.
ContactForm.prototype.ShowErrors = function( arrErrors ){
	var strError = "Please review the following:\n";
 
	// Loop over each error to build up the error string.
	$.each(
		arrErrors,
		function( intI, strValue ){
			strError += ("\n- " + strValue);
		}
		);
 
	// Alert the error.
	alert( strError );
}
 
 
// Define a method to submit the form via AJAX.
ContactForm.prototype.SubmitForm = function(){
	var objSelf = this;
 
	// Submit form via AJAX.
	$.ajax(
		{
			type: "get",
			url: "./api/Contacts.cfc",
			data: {
				method: "AddContact",
				name: this.DOMReferences.Name.val(),
				hair: this.DOMReferences.Hair.val()
				},
			dataType: "json",
 
			// Define request handlers.
			success: function( objResponse ){
				// Check to see if request was successful.
				if (objResponse.SUCCESS){
 
					// Clear the form.
					objSelf.Form.get( 0 ).reset();
 
					// Trigger the update event. This will allow
					// anyone who is listening for this event on
					// the document to react to it and update their
					// own display if needed.
					$( document ).trigger( "contactsUpdated" );
 
					// Focus the name field.
					objSelf.DOMReferences.Name.focus();
 
				} else {
 
					// The response was not successful. Show
					// an errors to the user.
					objSelf.ShowErrors( objResponse.ERRORS );
 
				}
			},
 
			error: function( objRequest, strError ){
				objSelf.ShowErrors( [ "An unknown connection error occurred." ] );
			}
		}
		);
}
 
 
// ----------------------------------------------------- //
// ----------------------------------------------------- //
 
 
// When the document is ready, init contact form. It is important
// that we wait for the DOM loaded event to that we have access to
// the DOM elements.
$(
	function(){
 
		// Create an instance of the contact form.
		var objContactForm = new ContactForm();
 
	}
	);

For Cut-and-Paste