Handling Ajax Requests With One Simple Class

Date Published: 25/02/2009 23:06

When starting out in the world of Ajax it can all seem a little overwhelming and that first Ajax script you write can often become heavy with excess code. The main problem comes from having to write separate functions for each HTTP request you make, handling the response and dealing with the age old problem of will it work in Internet Explorer. To combat this issue I have written a small (less than 30 lines) javascript class which cuts out the clutter and allows you to streamline your Ajax scripting down to the bare bones.

The Ajax Request Class

Here is the AjaxRequest class I have written, simply copy paste this into your script above where the calls will be made. I personally keep this class in my script library along with all the functions I use regularly and then use document.write() to include it at run time.

function AjaxRequest(url, completeFunction) {
var request = this;
var request_url = url;
this.callback = completeFunction || function () { };
this.post = function(params) {
request.http = null;
if (window.XMLHttpRequest) {
request.http = new XMLHttpRequest();
} else {
request.http = new ActiveXObject("Microsoft.XMLHTTP");
}
if (request.http == null) {
return false;
}
else {
request.http.onreadystatechange = function() {
if (request.http.readyState == 4 && request.http.status == 200) {
request.callback(request.http.responseText, request.http.status, request.http.responseXML);
request.http = null;
}
}
request.http.open("POST", request_url, true);
request.http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.http.setRequestHeader("Content-Length", params.length);
request.http.send(params);
return true;
}
}
}

Usage

With the above class in your script all Ajax requests can be cut down to the minimum number of lines. First we must define how we are going to handle the response when the request has completed. This must become before your AjaxRequest object is created so that it can be referenced. Here is an example of a sample response function which simply alerts the response which was received.

function responseFunction(responseText, responseStatus){
alert(responseText);
}

The responseText variable is whatever was returned by the HTTP request, this may be just a few words echoed out in a PHP script or a full XML document which can be parsed and used to change the existing page. The responseStatus variable is the HTTP request status. Next we need to create an instance of the AjaxRequest class we have created which we can do with the following line:

var ajax = new AjaxRequest("request/url", responseFunction);

This line takes the url which will be the basis of our request and a response function. The response function is what will be run when the HTTP request has been completed and a response has been received. This line does not however trigger the request, it simply gets it ready for transmission, we now need to setup our post variables and send the request.

ajax.post("param1=10&param2=20&param3=30");

This post request is sending 3 post parameters to the server, these are combined into a string and separated by ampersands (much like constructing a query string). If you are posting to a PHP script you will be able to retrieve these parameters as follows:

<?php
$param1 = $_POST["param1"];
$param2 = $_POST["param2"];
$param3 = $_POST["param3"];
echo $param1 . " " . $param2 . " " . $param3;
// Returns "10 20 30"
?>

By putting all this together along with a small PHP script containing the PHP code above which the request can be aimed at now results in an Ajax request which once complete opens an alert window stating "10 20 30". Not bad for a small class and a few lines of JavaScript.

Alternative Methods

There are of course other ways of achieving the same result as we have here using existing JavaScript libraries. The likes of jQuery, Dojo and YUI are all excellent and comprehensive JavaScript libraries which all support Ajax along with many other highly useful features. When minified (the process of reducing a JavaScript file down to the bare minimum by removing unnecessary white space and line breaks) these libraries can also have very small file sizes so not to consume your precious bandwidth. When asked why I don not use such libraries when I clearly promote their benefits I have one simple answer. I am a coding purist. When I write something I want to know everything about how it works and I want every line to be absolutely necessary. Using code snippets like mine is fine to complete individual tasks but using a large amount of foreign code for me is not an option.

Conclusion

Ajax has the potential to provide massively improved functionality to websites without harming accessibility. Doing a similar thing in flash would mean an entire rebuild in HTML to allow non-flash compatible browsers to access the content. Look at what the likes of google and facebook have achieved using Ajax technology, full blown applications from the safety of your browser. However, always remember to never build your sites entirely for Ajax. Always build a plain HTML version first and simply add functionality using Javascript and Ajax, that way you will never leave users out in the cold.

Comments

Sorry comments are currently disabled for maintenence

5 Most Recent Articles

Manually Triggering Events in ASP.NET from JavaScript

A quick guide for ASP.NET developers on how to manually trigger ASP.NET events from JavaScript.

Advanced Use of MySQL Stored Procedures

An article for users of MySQL databases describing how they can use advanced stored procedures to improve efficiently in their applications.

Using MySQL Stored Procedures and Extending MySQLi in PHP

A guide for LAMP developers to using stored procedures in MySQL and extending the MySQLi class.

Reading and Writing to Excel Spreadsheets in Python

An introduction to using the xlwt and xlrd modules for python to interact with Microsoft Excel spreadsheets.

Interact with the Web Using Python and the HTTP Library

This is an introduction to making HTTP requests from a python script/application using httplib.

Sponsors