|
AJAX |
||||||||
|
Home
Products Product Comparisons Features Screen Shots Downloads Updates Free License Support Solutions FAQ Papers AJAX JSON Editors Java HTML Perl JSP JavaScript PHP VBScript Velocity XML |
The AJAX term was coined by Garrett. It stands for Asynchronous JavaScript And XML and is somewhat misnamed since XML is not required. One use of AJAX is to let you build web pages that are more like traditional client based applications. For example, with AJAX you can auto complete an input element using data from a server. These applications are called internet applications. You will also hear them referred to as Web 2.0 applications. Another use of AJAX is to eliminate full page reloading when only part of a page needs to be updated with data from a server. In this tutorial we will show you how you can use AJAX to record and then show the results of a poll, vote, user preference, yes/no choices or ratings submissions in a page. We will also identify some of the issues facing AJAX developers. To see where we are going, try the following poll. You should see a bar chart showing the current votes. Do you prefer cats or dogs? The key technology that makes AJAX work is the XMLHttpRequest JavaScript object. The XMLHttpRequest was first implemented by Microsoft as an ActiveX object in IE 5.0 (March 1999). Then Mozilla added a compatible XMLHttpRequest object for Mozilla 1.0 and Netscape 7 (May 2001). This was followed by Apple's support in Safari 1.2 (February 2004) and Opera's support in version 8.5 (September 2005). Here is the AJAX sequence diagram that shows how the XMLHttpRequest is used.
The AJAX process starts with a DOM event. In step 1 you need to obtain a XMLHttpRequest object. This is typically done using a function like the following so that the code will work on different browsers:
function GetXMLHttpRequest()
{
var object = null;
if (window.XMLHttpRequest)
{
object = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
try
{
object = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
}
if (object == null)
{
try
{
object = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
}
}
}
if (object == null)
{
alert("Your browser does not support AJAX");
}
return object;
}
After you have the XMLHttpRequest object, you then need to set the 'onreadystatechange' callback function and call the 'open' and 'send' methods using code:
XMLHttpRequestObject.onreadystatechange = ProcessRequest;
XMLHttpRequestObject.open("GET", url, true);
XMLHttpRequestObject.send(data);
Note that the data that you send and receive when using the XMLHttpRequest object can be in any format. It does not need to be XML. We recommend that you look at JSON in place of XML. JSON is a subset of the literal object notation in JavaScript that includes many of the features of XML. If your application is fairly simple you could also use traditional name value pairs. At the end of step 1 you should provide the user some visual indication that something has changed. In the examples on this page we rename the Vote button to Loading... In step 2 you will need to have a handler that processes your request on the server. The handler can be a CGI or other server side script such as PHP, ASP, or JSP. In step 3 you will need to process the response using your ProcessRequest function. It should look something like the following:
function ProcessRequest()
{
if (XMLHttpRequestObject.readyState == 4)
{
if (XMLHttpRequestObject.status == 200)
{
var result = Parse();
if (result)
{
// Update HTML based on the result
}
}
else
{
// An error has occurred.
}
}
}
Be sure to check ready state and status codes since the handler will be called with different ready states and status codes. In this tutorial we are only interested when the call is complete. Important: Because the ProcessRequest function is being used as a callback you do not have control over when or if it will be called. Possible XMLHttpRequestObject.readyState codes are:
XMLHttpRequestObject.status codes are just HTTP status codes. ExamplesThe AJAX example below lets a user enter a vote and then see the results. To try it choose your color and then press the Vote button. Choose your favorite color: The code to display the choices for choosing your favorite color looks like this: <div id="colorvotediv"> Parameters are passed to the AJAX enabled OnVote function using custom attributes. The OnVote function locates the vote box by looking for an 'ID' of voteName + 'div' which results in the ID 'colorvotediv' for the div above. Each of the input tags must have the 'name' attribute set to voteName. The 'value' attribute should be a legal JavaScript variable name. The 'barcolor' attribute specifies the color of the resulting bar and the 'label' attributes specifies the bar label. It is easy to change the vote by just changing the HTML in the div tag. Here is another example that asks for your favorite language. Choose you favorite language The CodeBesides the utility functions there are two main functions for this example. The OnVote function sets up the AJAX process for a vote. It is triggered when the user clicks on the Vote button. The OnVoteProcess function is the callback that is responsible for processing the data and generating the bar chart. Both functions use a common global array XMLHttpRequestObject to maintain the vote data keyed by the votename. The OnVote function starts by getting the XMLHttpRequest and then initializing the array element XMLHttpRequestObject[votename]. It then defines the url that will be used to save and get the vote data from the server. Since we are using the 'GET' method we must append the data to the url. In this tutorial we are using a list of variable=value pairs separated by '&'. At the same time we save the bar color and label in the XMLHttpRequestObject[votename] object. Then we open the url, set the request header and call send. At this point the browser waits for a new event.
function OnVote(votename, title)
{
if (XMLHttpRequestObject == null)
{
XMLHttpRequestObject = new Array;
}
if(XMLHttpRequestObject[votename] != null)
{
return;
}
var requestObject = GetXMLHttpRequest();
if (requestObject)
{
XMLHttpRequestObject[votename] = new Object();
XMLHttpRequestObject[votename].requestObject = requestObject;
XMLHttpRequestObject[votename].title = title;
XMLHttpRequestObject[votename].color = new Array();
XMLHttpRequestObject[votename].label = new Array();
requestObject.onreadystatechange = new Function ("OnVoteProcess('" + votename + "')");
var url = URL + "?" + "votename=" + votename +
'&' + "vote=" + (document.cookie.length > 0 ? 'true' : 'false');
var voteChoices=document.getElementsByName(votename);
for(var i=0; i < voteChoices.length; i++)
{
url += '&' + voteChoices[i].value + '=' + (voteChoices[i].checked ? 1 : 0);
XMLHttpRequestObject[votename].color[i] = voteChoices[i].getAttribute('barcolor');
XMLHttpRequestObject[votename].label[i] = voteChoices[i].getAttribute('label');
}
requestObject.open("GET", url, true);
requestObject.setRequestHeader( "Content-Type" , "application/x-www-form-urlencoded; charset=UTF-8" );
requestObject.send("");
}
}
The second function is the OnVoteProcess function. It is the callback function that is called by the XMLHttpRequest object. In this case the OnVoteProcess function processes the vote data returned by the server and then builds a bar chart using a custom BarChart JavaScript class. Here is the code:
function OnVoteProcess(votename)
{
if (XMLHttpRequestObject[votename].requestObject &&
XMLHttpRequestObject[votename].requestObject.readyState == 4)
{
if (XMLHttpRequestObject[votename].requestObject.status == 200)
{
var result = XMLHttpRequestObject[votename].requestObject.responseText;
if (result == "busy")
{
alert("The server is busy. Try again.");
XMLHttpRequestObject[votename] = null;
}
else
{
var variables = result.split('&');
// Create an BarChart instance
var chart = new BarChart(XMLHttpRequestObject[votename].title, 70, 130, 18, "white");
for (var i = 0; i < variables.length; i++)
{
var variable = variables[i];
var item = variable.split('=');
chart.addBarData(XMLHttpRequestObject[votename].label[i],
item[1], XMLHttpRequestObject[votename].color[i]);
}
var name = votename + "div";
var divContainer = document.getElementById(name);
if (divContainer)
{
// Generate HTML for the BarChart using the DOM
chart.replace(divContainer);
}
XMLHttpRequestObject[votename] = null;
}
}
}
}
The remaining piece of the code is the server side code that records the vote. For this tutorial, we used a PHP script, but we could just as easily used any server side code, including C/C++, to record the vote. SecurityThe XMLHttpRequest object uses the same domain security policies as JavaScript. This means that the domain of the URL used for the XMLHttpRequest object must be the same as the as the server providing the page in order to avoid security warnings or failures (depending upon the browser). This means that client side scripts cannot conveniently use the XMLHttpRequest object to directly obtain information from other domains without getting a security warning. One workaround would be to use server side code installed on your server to specifically obtain the data from other servers. Uses of AJAXAJAX has many potential uses. Here are a few of them:
Don't forget DHTML and JavaScriptDHTML and JavaScript can offer many useful data and visual manipulation without needing to communicate with a server. See Rico for a JavaScript library of interesting effects. Rico also includes an open AJAX library. Integration with Other TechnologiesKeep in mind that you don't need to use AJAX for all communication with your server. For example, if you just want to log data to your server then you can use the image tag like this:
if (document.images)
{
var image = new Image(1,1);
image.src = "http://someplace.com/cgi-bin/mylog.cgi?" + data;
}
This is the technique that Google(tm) Analytics and others are using to record web site statistics. Even though this technique is often derisively referred to as a web bug, we recommend using this technique for internet applications so you can have some insight into what your users are doing. You could even combine AJAX and the image tag technique to provide real-time monitoring of your site. The TechnologyAs with all technology, there are issues that you will need to deal with when using AJAX. Some of these issues include:
ConclusionIn this article we have shown you how you can use AJAX to record and then show the results of a poll or vote. And we have identified some of the issues that AJAX developers will face. Please rate this article |
||||||||
|