Simplifying AJAX

Simplifying AJAX

By: Dan Burtchett

 


With the Web 2.0 frenzy, AJAX (asynchronous browser requests) has jumped in popularity across many websites -- avoiding the need of refreshing the entire page just to update content.

Unfortunately to achieve cross-browser compatibility you are forced to implement AJAX differently. Below are some JavaScript functions that I will explain on how to simplify AJAX for cross-browser compatibility.

The code below creates the AJAX Request object using a very simple cross-browser compatibility check

//
//  Create the AJAX request object
function createAJAXRequest()
{
     // If XMLHttpRequest is not avaliable, use IE ActiveX;
     if(window.XMLHttpRequest)
          return new XMLHttpRequest();
     else if(window.ActiveXObject)
     {
          try
          {
               return new ActiveXObject("Microsoft.XMLHTTP");
          }
          catch(msxml2)
          {
               return new ActiveXObject("Msxml2.XMLHTTP");
          }
     }
     return null;
}

The next block of code will create an AJAX connection to a specified URL,
and receive an XML response or error message

var contentTypeHeader = "Content-Type";
var postContentType = "application/x-www-form-urlencoded";

//
//  Making a connection using AJAX
function connect(url, params, method, contentType)
{
     // Acquires AJAX request object
     var request = createAJAXRequest();

     if(request)
     {
          // Default Method as "GET", if not set.
          if(!method)
               method = "GET";

          // Default "POST" Content-Type, if not set.
          if(!contentType && method == "POST")
               contentType = postContentType;

          try
          {
               // Set AJAX response processor event.
               request.onreadystatechange = function()
               {
                    processAJAXResponse(request);
               }

               // Open AJAX connection.
               request.open(method, url, true);

               // Set Content-Type, if type exists.
               if(contentType)
                    request.setRequestHeader(contentTypeHeader, contentType);

               // Set URL parameters, if params exists.
               if(params)
	               request.send(params);
          }
          catch(err)
          {
               // Add your own custom error handling here.
               alert("Error:\n" + err);
          }
     }
}
Once the connection has been established and your AJAX code placed its request, you will need to define an AJAX response processor function.

Below is example code for an AJAXResponseProcessor function

//
//  Processing AJAX response
function processAJAXResponse(request)
{
     var state = request.readyState;

     // If ready state is 4, server has processed the AJAX request
     if(state == 4)
     {
          var httpStatus = request.status;

          // If HTTP status is 200 or 0, communication was successful;
          // otherwise, it has resulted in an error
          if(httpStatus == 200 || httpStatus == 0)
          {
               // Get server response as XML
               var response = request.responseText;
               document.getElementById("answer").value = response;
          }
          else
          {
               // Add your own custom error handling here.
               alert("HTTP Error Code: " + httpStatus);
          }
     }
}
In the previous code examples, we simplied AJAX to: createAJAXRequest, connect, and processAJAXResponse.
The web calculator example below will demonstrate this code in action.
<!-- Warning: The following example will not work if you have JavaScript disabled. -->

<script type="text/javascript">
function calculate()
{
	var value1 = document.getElementById("value1").value;
	var value2 = document.getElementById("value2").value;
	var operand = document.getElementById("operand").value;
	var url = "/ajaxwebcalc.php?value1=" + value1 + "&value2=" + value2 + "&operand=" + operand;	

	connect(url, null, "GET", null);
}
</script>

<b>AJAX: Simple Web Calculator: </b>
<input id="value1" type="text" maxlength="4" />
<select id="operand">
	<option value="add">+</option>
	<option value="subtract">-</option>
	<option value="multiply">*</option>
	<option value="divide">/</option>
</select>
<input id="value2" type="text" maxlength="4" />
<input type="button" name="equals" value="=" onClick="calculate()" />
<input id="answer" type="text" readonly />
Simply enter your values, select an operand, and click the equals button to return the result:

AJAX: Simple Web Calculator:      

SymplistekTM has licensed the source code listed in this article under the
GNU Lesser GPL; this keeps it free for all uses: commercial, public, or private.
For additional information regarding the licensing terms, please see our Privacy Policy
Please feel free to contact us with any inquiries or comments you might have about this article.