counter


Username:Password:
///////////////////////////////////

February 23, 2008

Creating Smart Forms with AJAX

Filed under: Ajax — admin @ 10:10 pm

Web forms are very important pieces of an application. They’re used for registration, logging in, or even payment for services. Kris Hadlock explains the importance of creating “smart” forms and how to use AJAX to improve the forms in your applications.

Introduction

When you first think about designing a form, it probably doesn’t seem very glamorous. But when you consider all of the possibilities for user feedback, things get a little more interesting. Forms are usually very important, especially when dealing with web applications—this is where users register, login, provide useful data, or even pay you for a service. These important processes may be difficult for a user. That’s why it’s essential to streamline such processes and provide direct and useful information for user interactions.

NOTE

This article assumes that you have intermediate knowledge of JavaScript objects and AJAX. If you need more information about AJAX, read my article “How To Use AJAX.”

The source code for this article contains an AJAX engine that consists of three JavaScript objects. I won’t cover these objects in detail, but will explain how to incorporate them in this project. A sample for this article can be found here and the source can be downloaded here.

Creating a Form

We’re going to start by creating a simple registration form with HTML. The form contains input text boxes for first and last name, email address, username, and password:

<div id="Register">
    <form id="SmartForm" method="post" onsubmit="return false;">
       <div class="label">First Name:</div> <input id="firstName" type="text" />
       <br/><br/>
       <div class="label">Last Name:</div> <input id="lastName" type="text" />
       <br/><br/>
       <div class="label">E-mail:</div> <input id="email" type="text" />
       <br/><br/>
       <div class="label">Username:</div> <input id="username" type="text" />
       <br/><br/>
       <div class="label">Password:</div> <input id="password" type="password" />
       <br/><br/>
       <input type="submit" value="Register" id="submit" disabled />
       <br/>
    </form></div>

Now that we’ve created our form, we’ll create an XML file that will represent the users of our application.

Server-Side Code

The server-side code in this example will be an XML file that contains all of the user data. In a real application, this XML file probably would be generated on the server side based on database information, which would make it more secure and reusable. The XML file will contain the first and last name, email address, username, and password, just as our form does:

<?xml version="1.0" encoding="iso-8859-1" ?>
<users>
    <user firstName="Kris" lastName="Hadlock" email="mail@mail.com" username="kris" password="hadlock" /></users>

Next, we’ll gather user data and compare it with the values saved in this file.

Comparing the Data

To compare the data, we’ll create a JavaScript object called Validator and import it into our HTML file along with the AJAX engine objects and a CSS file that we’ll create later:

<script type="text/javascript" src="js/model/AjaxUpdater.js"></script>
<script type="text/javascript" src="js/model/HTTP.js"></script>
<script type="text/javascript" src="js/model/Ajax.js"></script>
<script type="text/javascript" src="js/view/Validator.js"></script>
<link href="css/smartform.css" rel="stylesheet" type="text/css" />

The Validator object needs to be created and then initialized. The initialize method will set local variables for the object to be used later when we validate the data. The parameters include the ID of the form, the number of fields that we’ll be validating, and the ID of the submit button, which in our case is the register button:

Validator = new Object();

Validator.initialize = function(formId, fieldNum, submitId)
{
    Validator.currentSelector = ’’;
    Validator.currentForm = formId;
    Validator.fieldNumToValidate = fieldNum;
    Validator.submitId = submitId;
}

This method will be called in the onload event of the body in our HTML file:

<body onload="Validator.initialize(’SmartForm’, 5, ’submit’);document.getElementById(’SmartForm’).reset();">

The next method that we’ll add to the Validator is called validate. This method will take an HTML element as the selector, along with the element’s value. If these parameters exist, we set the currentSelector and call a method called Update in the AjaxUpdater object. The Update method will make an XML HTTP Request to the users.xml file and set a local Validator method, called onValidation, as a callback:

Validator.validate = function(selector, value)
{
    if(selector && value)
    {
       Validator.currentSelector = selector;
       AjaxUpdater.Update("GET", "services/users.xml", Validator.onValidation);
    }
}

The onValidation method will fire when the response occurs. If the ready state passes, we’ll iterate the user and check for a matching value from the current input field (currentSelector). When we have a match, we’ll set the border color of the input field to red to show that the data already exists; when we don’t have a match, we’ll set it to green for success. This method can be modified to display any data at this point. For instance, we can display a message stating that the field data is currently being used, and so on. I chose to keep this example simple, to allow you to build on it.

Validator.onValidation = function()
{
    if(Ajax.checkReadyState(’loading’) == "OK")
    {
       var users = Ajax.getResponse().getElementsByTagName(’user’);
       for(var i=0; i<users.length; i++)
       {
           var value = users[i].getAttribute(Validator.currentSelector.id);
           if(value.toLowerCase() == Validator.currentSelector.value.toLowerCase())
           {
              Validator.currentSelector.style.borderColor = "#ff0000";
           }
           else
           {
              if(Validator.currentSelector.style.borderColor != "#009900")
              {
                  Validator.currentSelector.style.borderColor = "#009900";
                  Validator.fieldNumToValidate--;
              }
           }
           Validator.currentSelector.style.borderWidth = "2px";
       }

       if(Validator.fieldNumToValidate == 0)
       {
           document.getElementById( Validator.submitId ).disabled = false;
       }
    }
}

For our example, we’ll add the validate method to the onblur event from each input field. This will fire each time a user presses Tab or clicks out of an input field, which will then validate the value against the XML:

<div id="Register">
    <form id="SmartForm" method="post" onsubmit="return false;">
       <div class="label">First Name:</div> <input id="firstName" type="text" onblur="javascript:Validator.validate(this, this.value);" />
       <br/><br/>
       <div class="label">Last Name:</div> <input id="lastName" type="text" onblur="javascript:Validator.validate(this, this.value);" />
       <br/><br/>
       <div class="label">E-mail:</div> <input id="email" type="text" onblur="javascript:Validator.validate(this, this.value);" />
       <br/><br/>
       <div class="label">Username:</div> <input id="username" type="text" onblur="javascript:Validator.validate(this, this.value);" />
       <br/><br/>
       <div class="label">Password:</div> <input id="password" type="password" onblur="javascript:Validator.validate(this, this.value);" />
       <br/><br/>
       <input type="submit" value="Register" id="submit" disabled />
       <br/>
    </form>
</div>

Conclusion

Smart forms are pretty easy to create once you have a JavaScript object in place. At this point, the object can be imported into any form, and the validate method can be customized to respond however you want.


No Comments

No comments yet.

RSS feed for comments on this post. TrackBack URI

Sorry, the comment form is closed at this time.