One of the least user friendly features of most websites is forms. The longer the form, the more annoying it gets. However, a new technology called AJAX (that has nothing to do with household cleansers!) can help.
Let's face it. Using forms on the Internet is a drag. This is especially true when the form is really long and spread over multiple pages. Every time you hit the "submit" or "continue" buttons, there is a long user-unfriendly wait.
It doesn't have to be this way. A relatively new technology called AJAX (Asynchronous Javascript and XML) can allow an HTML form to submit contents to a server without a page re-load.
AJAX opens up enormous possibilities for Web applications simply by allowing HTTP requests to be made in the background asynchronously (while other scripts on the page run and other user activity continues).
AJAX Technology
AJAX technology is based on a Javascript Object called XMLHTTPRequest. Amazingly enough. XMLHTTPRequest is not a standard part of Javascript or the DOM. The fact that this object is supported by Internet Explorer 5.5, Mozilla/Firefox, Safari 1.2 and Opera 7 is a testament to just how useful this technology can be.
The W3C Load and Save Specification allows for similar functionality. Load and Save is not currently implemented in any Web browsers. When it is, however, both Load and Save and XMLHTTPRequest will likely be implemented in most browsers.
What's Out There Now
Both Google and Amazon have been pioneers in developing AJAX applications. Google's GMail, Suggest, and Google Maps all use AJAX in one way or another to make the Web user interface more like a desktop application.
The documentation for the request object is a little slim, and assumes a certain amount of knowledge of at least HTTP in order to get the most out of it. This article will attempt to lay out as many specifics about the use of XMLHTTPRequest as possible to enable you to use it to its full potential, with a focus on how to use it with forms.
The Basics
The request object (as we will try to call it from now on) is a special Javascript object that can be used in the same way that many such objects can be used. The only difference in implementation is in Microsoft Internet Explorer. In Explorer the request object is an Active X control. A simple example of how to deal with this difference is below.
var doc = null
if (typeof window.ActiveXObject != 'undefined' )
{
doc = new ActiveXObject("Microsoft.XMLHTTP");
doc.onreadystatechange = displayState;
}
else
{
doc = new XMLHttpRequest();
doc.onload = displayState;
}
If we are using IE, an instance of the Active X object is created and the onreadystatechange event is attached to it. If, however, it is just a plain old Javascript object, we create an instance of it and attach the onload event.
A function called displayState is called when the readystate changes or, in the case of the non-Active X object, the onload event is fired. Aside from these differences, everything is cross browser compatible. Except for one thing.
The XML in HTTPRequest
Though this object has XML in its name, it doesn't necessarily have to use XML. If you wish to use it in an entirely cross platform way, however, consider that currently Apple's Safari requires that the response from the server be of the text/xml mimetype.
This may or may not impact your application design. It isn't hard to set up an XML formatted response and code to use the XML data once it's received, but if you were planning on sending text strings only back and forth, this is something to consider. It's likely that the next version of Safari will not have this problem, and working around it is nothing compared to most cross browser DHTML problems. Sending information as a string, on the other hand, works in all platforms and browsers that support the request object.
The fact that the request object supports XML allows it to be the gateway for a number of XML based message formats, such as SOAP and XMLRPC, or your own custom solutions. Because the request object uses HTTP, you could also use it with WEBDAV if you were so inclined. If you are only retrieving XML from the server and not sending anything, you can even use AJAX without a server side application platform. The implementation details are up to you, but the tools are there.
The Event Handler
Whatever event handler function you specify should check for two things. The first is the readyState property. If readyState is 4, then the response has been completely recieved. You then need to check the status property of the request object to determine whether the request was successful. If the value of status is 200, any data that was sent back as a response is ready for use. If status is something other than 200, you will be able to display the error by using the statusText property.
The response, as mentioned before, can be a simple text string or an XML document DOM (Document Object Model). The two request object response properties you will use for working with a response are responseText and responseXML. The DOM object stored in responseXML is a completely accessible DOM that can be manipulated and traversed in the same way that your HTML document can be. The responseText property is used when a simple text string is sent by the server.
Accessing the XML file through the usual limited DOM methods provided for HTML is no fun. The European Computer Manufacturers Association, or ECMA, who is responsible for the ECMA script standard on which Javascript is based, has just introduced a new extension to ECMA called E4X which is especially designed to work with XML documents. E4X includes support for XPath, which is a W3C recommendation for addressing information within an XML document. Currently, there are no browsers that support E4X. The first browser to support it will be Firefox 1.1. Unfortunately, until E4X truly arrives, traditional DOM methods are all we have.
HTTP Methods
The request object supports both POST and GET as well as other HTTP methods.
Using the GET method is the simplest to implement.
In a GET request, all information is contained in the URL. It is encoded to escape characters and spaces that are not allowed in URLs by representing them as their hexadecimal equivalents preceded by "%". The information is formatted as key-value pairs in the following way.
http://www.mydomain.com/?id=215&status=true
To encode a value you can use the Javascript function escape(). To encode an entire URL, use encodeURI. Keep in mind that encodeURI is part of Javascript 1.5, and is only supported by browsers that also support this version of Javascript.
Once you have a properly formatted string of values that has been tacked onto the end of the URL, you can use the open method of the request object to start the process of sending the request.
var str = http://www.mydomain.com/index.php?pet=dog&hobby=painting;
xmlReq.open("GET",str,true);
The variable str is shown here as a hard coded string, however in practice it's likely that you will be compiling it from other code. The open method takes three arguments. The first is the HTTP method as a string. The second is the URL string, and the third is a boolean value. This third parameter determines whether or not the request is done asynchronously. If the need arises to ask the user to wait for a request to finish, you could set this argument to false; otherwise, it should be set to true.
The send() Method
The send method is the final stage for sending the request. It takes one argument but in the case of a GET request that value is not needed. Instead this argument should be null.
xmlReq.send(null);
If you were using the POST method, the argument for send() can be a string or an XML DOM object. This allows you to send a string of text or a serialized XML document as part of the body of your request.
Using POST
Using POST with the request object is a little different. One thing that does not need to change is the format and encoding of the actual information you are sending. In this case, what was the query string is put into the body of the request as an argument to the send method, and the URL remains as an argument to the open method.
var str = "pet=dog";
var url = "http://www.mydomain.com/index.php";// No question mark needed
xmlReq.open("POST",url,true);
xmlReq.send(str);
You will notice if you test this with PHP that the information from this request will not come up in the $_POST or $HTTP_POST_VARS global variables. To access it, you must use $HTTP_RAW_POST_DATA, depending on your php.ini settings. The form of the information will be the string that you sent with the request. In order to use it as key-value pairs, you would have to manually split the string. How this works in ASP, ASP.net, JSP and other server platforms will vary. In order to get the request body values to show up in $_POST as they would from a normal form, you will need to use an additional method of the request object called setRequestHeader().
var str = "pet=dog&hobby=painting";
var url = "http://www.mydomain.com/index.php";// No question mark needed
xmlReq.open("POST",url,true);
xmlReq.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded; charset=UTF-8");
xmlReq.send(str);
Using this header lets the server know that the string of characters in the body of the request is an encoded string of key-value pairs. The information is then handled in the same way as a normal POST form submission.
The open, setRequestHeader and send methods assemble the proper HTTP headers from the information you provide them. The first argument of setRequestHeader is the type of header; the second is the header itself. There is no need to add a ":" between the two, as this is done by the method itself. The header set with this method can be any valid HTTP header.
Submitting a Form
Normally forms don't need any additional code to submit information, aside from any validation code that you choose to use. In this case, however, we will need to write some code to gather information from the form, and possibly from other areas of the application, to put into the proper format. One advantage this has over normal form submission is that you can include information that is not part of the form. No hidden form fields are necessary to make this work.
As an example, let's take a simple form to allow a user to request a product catalog by mail (you remember mail: paper, stamps, etc.).

The submission can start out at the click of a button or link. The button should be a normal form button rather than a submit button because in this situation we aren't using the browser's built in form submission. When the user clicks on the form button, the "sub" function is called, which begins the processing of the information and submits it to the server.
var xmlReq = null;
function sub(f)
{
var file = 'testPost.php'
var str = getFormValues(f,"validate");
xmlReq = getXML(file,str);
}
function getXML(file,str)
{
var doc = null
if (typeof window.ActiveXObject != 'undefined' )
{
doc = new ActiveXObject("Microsoft.XMLHTTP");
doc.onreadystatechange = displayState;
}
else
{
doc = new XMLHttpRequest();
doc.onload = displayState;
}
doc.open( "POST", file, true );
doc.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
doc.send(str);
return doc;
}
The HTML for the form is simple. There is no need to set any form attributes.
<form>
<label>Your Name<input type="text" id="text" name="name"></label>
<br><br>
<label>Your Address<input type="text" name="address"></label>
<br><br>
<label>
<select id="info" name="Catalog">
<option value="1">Full Product Catalog</option>
<option value="2">Spring Catalog</option>
<option value="3">Special Order Service</option>
</select> Select The Product Catalog you Want to Receive</label>
<br><br><br>
<input type="button" value="Request Information" onClick="sub(this.form)">
</form>
Fields for name, address and a select menu with catalog choices are provided. We will need to loop through each form element and retrieve a value. The following code does this, and provides a way for text fields to be validated.
function getFormValues(fobj,valFunc)
{
var str = "";
var valueArr = null;
var val = "";
var cmd = "";
for(var i = 0;i < fobj.elements.length;i++)
{
switch(fobj.elements[i].type)
{
case "text":
if(valFunc)
{
//use single quotes for argument so that the value of
//fobj.elements[i].value is treated as a string not a literal
cmd = valFunc + "(" + 'fobj.elements[i].value' + ")";
val = eval(cmd)
}
str += fobj.elements[i].name +
"=" + escape(fobj.elements[i].value) + "&";
break;
case "select-one":
str += fobj.elements[i].name +
"=" + fobj.elements[i].options[fobj.elements[i].selectedIndex].value + "&";
break;
}
}
str = str.substr(0,(str.length - 1));
return str;
}
This function accepts two arguments. The first is a reference to a form object, the other is the name of a validating function in the form of a string. The elements array of the form object is looped through, and a switch construct decides what to do with each of the relevant types of form elements (in this case just text and select-one). If the element is a text field, the eval function is used to call the validating function that is specified by argument two, which is sent the value of the form element.
If you needed, for instance, to validate other types of elements, each in a unique way, you could include a second argument to the validating function that would be the name or type of the element, and allow the validating function to treat each element differently. The validating function could work in whatever way you wished it to, but it would be a good idea, if an error is found, to set a global variable to false. This variable could then be used to keep submission from occurring until the error was corrected. Form fields could be highlighted in some way if there was an error in them as well.
In addition to sending the element value to a validating function, getFormValues assembles the values into a compatible querystring. The loop will add an extra "&" at the end of the string, which we clip off after the loop is finished. The string is then returned for use in our request.
Conclusion
AJAX technology can make browser based applications very close in functionality to standard desktop applications. Reference documentation for the XMLHTTPRequest object is available at XULplanet and Microsoft's MSDN website, and more information on XMLHTTPRequest, AJAX and examples of working applications are only a Web search away.
By Chris Root
Source: devarticles.com
