Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > Usability

Web Design Reference Guide

Hosted by

Toggle Open Guide Table of ContentsGuide Contents

Close Table of ContentsGuide Contents

Close Table of Contents

Designing With Code: Converting Forms to Ajax

Last updated Oct 17, 2003.

By Kris Hadlock

Web design has become more than just a pretty web site with a nice layout. While that's still part of the equation, web design has evolved into the way things work, how users interact with a web site or application, and how the entire experience is crafted. In this article, I'll show you how to take your old standard web forms and convert them to Ajax to enhance the experience in your applications.

Converting a standard form post to Ajax will require just a few steps once you have the files from this article. In this article, I'll show you how to create an Ajax engine, a JavaScript object that catches and reroutes the submit event through the Ajax engine, and a PHP file that handles the form submission and returns a response.

You can download the source files here and view a live preview here. We'll start by taking a brief look at the Ajax engine that's used in the example. If you'd like to get up to speed with some Ajax basics, you can take a look at some of my previous articles.

Ajax Engine

The Ajax engine (Listing 1) that we'll use throughout this example is completely self-contained, requiring us only to import it and call a method to make a request. The object is fairly small, with only two methods: Request and checkReadyState. The Request method takes four parameters: the method, URL, query, and callback method.

With these parameters, the method handles creating the XMLHTTP object, setting the callback method, passing the query string if one exists, and sending the request via the appropriate method type. The checkReadyState method handles checking the ready state and triggering the callback method that was passed via the Request method with the responseXML.

Listing 1: Ajax engine (Ajax.js)

var Ajax = new Object();
Ajax.isUpdating = true;

Ajax.Request = function(method, url, query, callback)
{
   this.isUpdating = true;
   this.callbackMethod = callback;
   this.request = (window.XMLHttpRequest)? new XMLHttpRequest(): new ActiveXObject("MSXML2.XMLHTTP"); 
   this.request.onreadystatechange = function() { Ajax.checkReadyState(); };
   
   if(method.toLowerCase() == ’get’) url = url+"?"+query;
   this.request.open(method, url, true);
   this.request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
   this.request.send(query);
}
   
Ajax.checkReadyState = function(_id)
{
   switch(this.request.readyState)
   {
     case 1: break;
     case 2: break;
     case 3: break;
     case 4:
        this.isUpdating = false;
        this.callbackMethod(this.request.responseXML.documentElement);
   }
}

With the Ajax engine in place we can start rerouting the posts through Ajax.

Rerouting Form Posts Through Ajax

In order to reroute a form post through Ajax, we must first gather the values in the form. To do this, we'll use an object called PostManager (Listing 2), which is accessed through the Send method.

The PostManager object takes only one parameter—the form element from the form that we want to reroute. It then builds a query based on the form values and sends the Ajax request. The Ajax request is sent with the following parameters—the forms method and action properties, the query we build from the values, and a callback method called OnResponse.

Listing 2: Handling form posts with JavaScript (PostManager.js)

var PostManager = new Object();
PostManager.Send = function(form)
{
   var query = PostManager.buildQuery(form);
   Ajax.Request(form.method, form.action, query, PostManager.OnResponse);
}

PostManager.OnResponse = function(xml)
{
   //alert(xml);
}

PostManager.buildQuery = function(form)
{
   var query = "";
   for(var i=0; i<form.elements.length; i++)
   {
     var key = form.elements[i].name;
     var value = PostManager.getElementValue(form.elements[i]);
     if(key && value)
     {
        query += key +"="+ value +"&";
     }
   }
   return query;
}

PostManager.getElementValue = function(formElement)
{
   if(formElement.length != null) var type = formElement[0].type;
   if((typeof(type) == ’undefined’) || (type == 0)) var type = formElement.type;

   switch(type)
   {
     case ’undefined’: return;

     case ’radio’:
        for(var x=0; x < formElement.length; x++) 
          if(formElement[x].checked == true)
        return formElement[x].value;

     case ’select-multiple’:
        var myArray = new Array();
        for(var x=0; x < formElement.length; x++) 
          if(formElement[x].selected == true)
             myArray[myArray.length] = formElement[x].value;
        return myArray;

     case ’checkbox’: return formElement.checked;
   
     default: return formElement.value;
   }
}

With the ability to parse a form to retrieve its values and properties we can now tie it together into HTML.

Tying It All Together

Now we're ready to create a simple HTML form to reroute through Ajax. The form can consist of any form element—an input, textarea, checkbox, radio button, etc. Listing 3 includes a simple example with an input and textarea.

Listing 3: HTML form (index.html)

<html>
<head>
   <title>Ajax Form</title>

   <script type="text/javascript" src="js/Ajax.js"></script>
   <script type="text/javascript" src="js/PostManager.js"></script>
</head>

<body>

<form action="posthandler.php" method="post" onsubmit="PostManager.Send(this); return false;">
   Name:<br/><input type="text" name="name" />

   <br/><br/>
   Message:<br/><textarea name="message"></textarea>
   <br/><input type="submit" value="submit" />

</form>

</body>
</html>

To reroute this form through Ajax, we need to import the appropriate JavaScript files. We'll then use the onSubmit event to reroute the form post to the PostManager objects' Send method.

You'll also notice the code return false after this method, which forces the form to not perform the usual post. That's it! The objects handle the rest, making this process completely reusable for other forms.

The real work comes on the server side and is based on how you handle the request. Let's take a look at a quick example of how to gather these values and return a simple response.

Handling the Request on the Server

The first step in responding to the Ajax request is setting the content-type to xml, which we'll do using PHP's header method.

Next, we need to decipher whether the Request method was a POST or GET and whether there were any query values. Once we've figured out the Request method, we'll set a variable named $request to the query parameters. If the request didn't include any parameters or query, we'll respond with a custom message. In this example, I'm requiring a query and sending an error back to the requestor. If a query exists, we'll respond with the values from the query string.

Listing 4: Handling the form post (posthandler.php)

<?php
   header("Content-Type: application/xml; charset=ISO-8859-1");
   
   if($_POST) $request = $_POST;
   else if($_GET) $request = $_GET;
   else
   {
     echo ’<error>no query</error>’;
     return;
   }
   
   $values = array();
   foreach ($request as $key => $value) 
   {
     array_push($values, $value);
   }
   
   echo ’<?xml version="1.0" encoding="ISO-8859-1" ?>’;
   echo ’<xml>’. implode(",", $values) .’</xml>’;
   
?>

This code is just an example of how you could parse the query string on the server—how you handle it and respond to the requestor is up to you.