A Basic Ajax Library
From Wiki
- AJAX stands for Asynchronous JavaScript And XML.
- AJAX is a type of programming made popular in 2005 by Google (with Google Suggest).
- AJAX is not a new programming language, but a new way to use existing standards.
- AJAX is based on JavaScript and HTTP requests.
- With AJAX you can create better, faster, and more user-friendly web applications.
- AJAX is based on the following web standards: JavaScript, XML, (X)HTML, CSS
- With AJAX, your JavaScript can communicate directly with the server, using the JavaScript XMLHttpRequest object.
- With XMLHttpRequest, your JavaScript can exchange data with a web server, without reloading the page.
- AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server.
Contents |
The Role of JavaScript
JavaScript is the glue that holds your AJAX application together. It performs multiple roles in AJAX development:
- controlling HTTP requests that are made using XMLHttpRequest
- parsing the result that comes back from the server, using either DOM manipulation methods, XSLT, or custom methods, depending on the data exchange format used
- presenting the resulting data in the user interface, either by using DOM manipulation methods to insert content into the web page, by updating an XHTML element or by changing elements’ CSS properties
Using AJAX Libraries
Solution 1: Use an existing library of code.
Many libraries, toolkits, and frameworks are available and make XMLHttpRequest easier to use.
- http://code.google.com/webtoolkit/
- http://labs.adobe.com/technologies/spry/
- http://www.modernmethod.com/sajax/
Solution 2: Create your own library.
Creating your own library will help you to understand how the XMLHttpRequest class works, and will help you get more out of those other toolkits or libraries when you do decide to use them.
Properties of our Ajax class
-
request– the XMLHttpRequest object -
url -
method– the request method: GET or POST -
async– true if is an asynchronous method, otherwise, false -
responseFormat -
mimeType
function Ajax() {
//properties
this.request = null;
this.url = null;
this.method = 'GET';
this.async = true;
// 'text', 'xml', or 'object'
this.responseFormat = 'text';
this.mimeType = null;
}
Different browser implementations of XMLHttpRequest
- Firefox and Safari create XMLHttpRequest objects using a class called XMLHttpRequest
- Internet Explorer version 7 now supports the same interface as Firefox !
- Internet Explorer version 6 and earlier use a special class called ActiveXObject that’s built into Microsoft’s scripting engine.
- Although these classes have different constructors, they behave in the same way (implement the same interface)
Creating an XMLHttpRequest object
Our Ajax class provides an init() method which creates the XMLHttpRequest object:
this.init = function() {
if (!this.request) {
try {
// Try to create object for Firefox, Safari, IE7, etc.
this.request = new XMLHttpRequest();
} catch (e) {
try {
// Try to create object for later versions of IE.
this.request = new ActiveXObject('MSXML2.XMLHTTP');
} catch (e) {
try {
// Try to create object for early versions of IE.
this.request = new ActiveXObject('Microsoft.XMLHTTP');
}catch (e) {
// Could not create an XMLHttpRequest object.
return false;
}
}
}
}
return this.request;
};
Sending a HTTP Request
The method doRequest() makes a HTTP request:
- Create an XMLHttpRequest object (using
init()) - Setting up the HTTP Request by using the
open()method onthis.request(XMLHttpRequest instance) - Setting Up the
onreadystatechange()event handler - Sending the HTTP Request by using the send() method of the XMLHttpRequest class
Step1: Create an XMLHttpRequest object
this.doRequest = function() {
//Create an XMLHttpRequest object
if (!this.init()) {
alert('Cannot create XMLHttpRequest object.');
return;
}
//Setting Up the HTTP Request
// ....
};
Step2: Setting Up the HTTP Request
this.doRequest = function() {
//Create an XMLHttpRequest object
if (!this.init()) {
alert('Could not create XMLHttpRequest object.');
return;
}
//Setting Up the HTTP Request
this.request.open( this.method, this.url, this.async);
//Setting Up the onreadystatechange Event Handler
};
open( Method, URL, Asynchronous Flag); where:
-
Method- the type of HTTP request method ("GET", "POST") -
URL- the page being requested (or posted to if the method is POST). -
Asynchronous Flag– A Boolean. If this parameter is set totrue, your JavaScript will continue to execute normally while waiting for a response to the request. If you set the parameter tofalse, JavaScript execution will stop until the response comes back from the server.
Step3: Setting Up the onreadystatechange() Event Handler
As the HTTP request is processed on the server, its progress is indicated by changes to the readyState property. This property is an integer that represents one of the following states, listed in order from the start of the request to its finish:
- 0: uninitialized -
open()has not been called yet. - 1: loading -
send()has not been called yet. - 2: loaded -
send()has been called, but the response is not yet available. - 3: interactive - The response is being downloaded, and the
responseTextproperty holds partial data. - 4: completed - The response has been loaded and the request is completed (the
responseText/responseXMLproperty holds complete data).
this.doRequest = function() {
//Create an XMLHttpRequest object
if (!this.init()) {
alert('Could not create XMLHttpRequest object.');
return;
}
//Setting Up the HTTP Request
this.request.open( this.method, this.url, this.async);
//Setting Up the onreadystatechange Event Handler
var self = this; // Fix loss-of-scope in inner function
this.request.onreadystatechange = function() {
if (self.request.readyState == 4) {
// Processing the response
}
};
// Sending the HTTP Request
};
Step 4: Sending the HTTP Request
this.doRequest = function() {
//Create an XMLHttpRequest object
if (!this.init()) {
alert('Could not create XMLHttpRequest object.');
return;
}
//Setting Up the HTTP Request
this.request.open( this.method, this.url, this.async);
//Setting Up the onreadystatechange Event Handler
var self = this; // Fix loss-of-scope in inner function
this.req.onreadystatechange = function() {
if (self.request.readyState = = 4) {
// Processing the response
}
};
// Sending the HTTP Request
this.request.send(this.postData);
};
The send() method takes one parameter, which is used for POST data. When the request is a simple GET ( like our current request) we set this parameter to null.
Processing the Response
The content of the response can be accessed via two properties of our XMLHttpRequest object:
-
responseTextThis property contains the response from the server as a normal string. In the case of an error, it will contain the web server's error page HTML. -
responseXMLThis property contains an XML document object. If the response is not XML, this property will be empty.
Our Ajax class will be able to provide the response from the server in three differentformats:
- as a normal JavaScript string,
- as an XML document object accessible via the W3C XML DOM, and
- as the actual XMLHttpRequest object that was used to make the request.
A basic implementation of the onreadystatechange() is:
this.request.onreadystatechange = function() {
var response = null;
if (self.request.readyState == 4) {
switch (self.responseFormat) {
case 'text':
response = self.request.responseText;
break;
case 'xml':
response = self.request.responseXML;
break;
case 'object':
response = request;
break;
}
if (self.request.status >= 200 && self.request.status <= 299) {
self.handleResponse(response);
}else {
self.handleError(response);
}
}
};
//This is a simple implementation which just "paste" the response from the server.
//Here we assume a text response from the server.
this.handleResponse = function(response) {
document.body.appendChild(
document.createTextNode(response));
};
Error Handler(handleError())
this.handleError = function(response) {
var errorWin;
try {
errorWin = window.open('', 'errorWin');
errorWin.document.createTextNode(response);
}catch (e) {
alert('An error occurred, but the error message cannot be '
+ 'displayed. This is probably because of your browser\'s '
+ 'pop-up blocker.\n'
+ 'Please allow pop-ups from this web site if you want to '
+ 'see the full error messages.\n'
+ '\n'
+ 'Status Code: ' + this.request.status + '\n'
+ 'Status Description: ' + this.request.statusText);
}
};
Setting the Correct Content-Type
Implementations of XMLHttpRequest in all major browsers require the HTTP response's Content-Type
to be set properly in order for the response to be handled as XML.
- Well-formed XML, returned with a content type of text/xml (
application/xml,application/xhtml+xml), will properly populate theresponseXMLproperty of an XMLHttpRequest object; - non-XML content types will result in values of
nullorundefinedforresponseXMLproperty.
this.setMimeType = function(mimeType) {
this.mimeType = mimeType;
};
Aborting the Request
Sometimes, a web page will take a very long time to load. Your web browser has a Stop button, but what about your Ajax class?
this.abort = function() {
if (this.request) {
this.request.onreadystatechange = function() {
};
this.request.abort();
this.request = null;
}
};
All in one
- Type: http://localhost/TestAjax
- And the browser output will be such as:
Hello adrian. I am server localhost at 127.0.0.1. Currently I run PHP version 5.1.6. The current server date is January 29, 2007, 6:53 pm.
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>A Simple AJAX Test</title>
<script type="text/javascript" src="scripts/ajax.js"></script>
<script type="text/javascript">
var ajax = new Ajax();
ajax.doGet('server/demoserver.php', 'name=adrian');
</script>
</head>
<body>
</body>
</html>
demoserver.php
<?php
header('Content-Type: text/plain');
$name = $_REQUEST[name];
if ($name=='adrian'){
$date = date('F j, Y, g:i a');
$serverName = $_SERVER['SERVER_NAME'];
$serverAddress = $_SERVER['SERVER_ADDR'];
$ver = phpversion();
echo "Hello $name. I am server $serverName at $serverAddress. Currently I run PHP version $ver. The current server date is $date."
} else{
echo 'Unknown person!';
}
?>
ajax.js
Collect properly the above Javascript code and you'll have the entire Ajax class.

