AJAX is one of the most trendy terms in the information technology sector today and serves as the technical secret behind major applications like Google, Flickr, GMail, Google Suggest, and Google Maps. Although this term has only emerged in recent months, InfoWorld’s May 2005 issue stated that AJAX is creating a revolution in the web world.
WHAT IS AJAX?
JavaScript, the programming language that runs in browsers, has been familiar in the web world since Netscape invented it. The development of technology and rising user demands have forced developers to create a different technique that allows for more complex tasks. In February 2005, the term Ajax began circulating on the Internet as a new technique for web applications. The remarkable success and strange appeal of Gmail, Google Suggest, and Google Maps drew significant attention to Ajax.
Ajax stands for Asynchronous JavaScript and XML – a technique that combines two powerful features of JavaScript highly valued by developers:
• Sending requests to the server without reloading the page
• Parsing and working with XML
Ajax applications revolve around a feature called XMLHttpRequest. The engineers of the Mozilla project began supporting this feature in Mozilla 1.0 (and Netscape 7). Apple also implemented a similar feature starting from Safari 1.2.
Ajax is a combination of a series of technologies that have recently attracted the attention of the industry. These include:
• Web page presentation based on XHTML and CSS, standards from W3C, well supported by Firefox (Mozilla), Safari (Apple), Opera, Netscape 8.0 (built on Firefox);
• Dynamic and interactive representation using Document Object Model, a W3C standard;
• Data exchange and processing using XML and XSLT, W3C standards;
• Asynchronous data retrieval using XMLHttpRequest;
• Using JavaScript to link everything together. Here, JavaScript refers to ECMAScript, a standard from ECMA, not Microsoft’s JScript.
In traditional web applications, the client sends an HTTP Request to the web server, and the web server responds with information in the form of HTML and CSS. AJAX allows for the creation of an Ajax Engine that sits between this communication. In this case, the requests to send and receive responses are managed by the Ajax Engine. Instead of returning data as HTML and CSS directly to the browser, the web server can send back data in XML, and the Ajax Engine will receive, parse, and convert it to XHTML+CSS for the browser to display. This process occurs on the client side, significantly reducing the load on the server while providing users with immediate processing results without needing to reload the page. Additionally, the combination of web technologies like CSS and XHTML greatly enhances the presentation of web interfaces and significantly reduces the amount of data that needs to be loaded. These are practical benefits that Ajax offers.
AJAX PROGRAMMING
Handling HTTP Requests
To send an HTTP Request to the server using JavaScript, you need to create an object of the class that provides this functionality. In Internet Explorer, this class exists as an ActiveX object named XMLHTTP. This object has been available since IE 4.0.
var httpRequest = new ActiveXObject(“Microsoft.XMLHTTP”);
If MSXML is installed, you can also call:
var httpRequest = new ActiveXObject(“Msxml2.XMLHTTP”);
In Mozilla, Firefox, Opera 8.0, Safari, and other browsers, this class is named XMLHttpRequest. The XMLHttpRequest object is not yet a W3C standard (it may be approved by W3C in the future). The XMLHttpRequest object is supported in IE 5.0+, Safari 1.2+, Mozilla 1.0+/Firefox, Opera 8.0+, and Netscape 7+.
var httpRequest = new XMLHttpRequest();
Due to these differences, to ensure your application runs on multiple browsers, you can do the following:
if (window.XMLHttpRequest) { // Mozilla, Safari, …
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
httpRequest = new ActiveXObject(“Microsoft.XMLHTTP”);
}
Because ActiveX in IE is very dangerous for users, in many cases this feature is disabled by default, so you need to check the user’s browser before calling the XMLHTTP object. This check is performed through the value of window.ActiveXObject. For example:
if (window.ActiveXObject) {
xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”)
}
else { …}
Some versions of Mozilla browsers do not function correctly when receiving a response from the server without a header containing the XML mime-type. To fix this issue, you can use the method to redefine the headers sent by the server in cases where it is not text/xml.
httpRequest = new XMLHttpRequest();
httpRequest.overrideMimeType(text/xml);
Next, you need to specify what you want to do after receiving the response from the server. At this stage, you simply inform the HTTP request object which JavaScript function will handle the response. This is done by setting the onreadystatechange property of the object to the name of the JavaScript function:
httpRequest.onreadystatechange = nameOfTheFunction;
Note not to use parentheses () after the function name and do not pass parameters to that function. Additionally, instead of providing the function name, you can use the technique of defining a dynamic function:
httpRequest.onreadystatechange = function() {
// do the thing
};
After you have declared what will happen when receiving the response, you proceed to send the request. You need to call the open() and send() methods of the HTTP request class:
httpRequest.open(GET, http://www.example.org/some.file, true);
httpRequest.send(null);
The first parameter of the open() call is the HTTP Request method – GET, POST, HEAD, or any method you want to use that the server supports. Be sure to write it in uppercase according to the HTTP standard; otherwise, some browsers like Firefox may not process the request.
The second parameter is the URL of the page to which you are sending the request. Due to security settings, you cannot call pages on a third-party domain. Note that if you do not call the correct domain across all pages, you will receive a permission denied message when calling open().
The third parameter establishes whether the request is asynchronous or not. If TRUE, the execution of the JavaScript function will continue while the server’s response has not yet arrived. This is the “A” in AJAX.
The parameter sent to the send() method can be any data you want to send to the server if you are using the POST method to send the request. The data should be in the form of a query string:
name=value&anothername=othervalue&so=on
The XMLHttpRequest object has a set of common properties across all supporting environments. Below is a list of the main properties of this object.
Handling Server Responses
Note when sending a request, you provide the name of the JavaScript function designed to handle the response.
httpRequest.onreadystatechange = nameOfTheFunction;
Let’s see what this function should do. First, the function needs to check the status of the request. If the status is 4, it means that your application has received a complete response from the server, which is a good sign to continue processing it.
if (httpRequest.readyState == 4) {
// no issues occurred and you have received the response
} else {
// not ready
}
Next, you need to check the status code of the HTTP server response. All possible codes can be referenced on the W3C site. In this article, we are particularly concerned with the response 200 (OK).
if (httpRequest.status == 200) {
// response status returns a good signal!
} else {
// there was a problem receiving and processing the request,
// for example 404 (Not Found)
// or 500 (Internal Server Error)
}
After checking the status of the request and the HTTP response status code, how to process the data sent by the server is up to you. You have two options:
• httpRequest.responseText – returns as a text string
• httpRequest.responseXML – returns as an XMLDocument object which you can traverse using JavaScript DOM functions
Example with Text Response
We will build a simple example. The JavaScript code sends a request to an HTML page, test.html. This page contains the line “I’m a test”, and then we use alert() to output the content of that file.
var httpRequest = false; // Initially no request
function makeRequest(url) {
httpRequest = false;
if (window.XMLHttpRequest) { // Check for XMLHttpRequest support in Mozilla, Safari,…
httpRequest = new XMLHttpRequest();
if (httpRequest.overrideMimeType) {
httpRequest.overrideMimeType(text/xml);
}
} else if (window.ActiveXObject) { // In IE, check if ActiveX is disabled
try {
httpRequest = new ActiveXObject(“Msxml2.XMLHTTP”);
} catch (e) {
try {
httpRequest = new ActiveXObject(“Microsoft.XMLHTTP”);
} catch (e) {
// Your alternative handling
}
}
}
if (!httpRequest) {
alert(Giving up 🙁 Cannot create an XMLHTTP instance);
return false;
}
httpRequest.onreadystatechange = alertContents;
httpRequest.open(GET, url, true);
httpRequest.send(null);
}
function alertContents() {
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
alert(httpRequest.responseText);
} else {
alert(There was a problem with the request.);
}
}
}
style=”cursor: pointer; text-decoration: underline”
onclick=”makeRequest(test.html)”>
In this example, the user clicks on the “Make a request” link in the browser, which calls the makeRequest() function with one parameter – the name test.html of the HTML file in the same directory. The request is then executed.
Next, you define the alertContents() function to handle the onreadystatechange event. alertContents() checks if the response has been received and if it is OK, it will execute alert() to output the content of the test.html file.
Example with XML Response
The example we just reviewed illustrates how to use the reponseText property of the request object. The following example will demonstrate the responseXML property.
The first step is to prepare the XML page that will be used for the subsequent request. The following page is named test.xml:
I’m a test.
In the code snippet above, we just need to replace the request line with:
…
onclick=”makeRequest(test.xml)”>
…
Then, in the alertContents() function, we need to replace the line alert(httpRequest.responseText); with:
var xmldoc = httpRequest.responseXML;
var root_node = xmldoc.getElementsByTagName(“root”).item(0);
alert(root_node.firstChild.data);
responseXML provides us with an XMLDocument object, and we will use DOM methods to access some data available in the XML page.
The example source code can be downloaded from the TGVT website, and you can also run it directly at http://goldenkey.edu.vn/ajax.
onreadystatechange | Event handler for an event that triggers every time the state changes. | ||||
readyState | Status: 0 = uninitialized 1 = loading 2 = loaded 3 = interactive 4 = complete | ||||
responseText | String data returned from the server | ||||
responseXML | DOM-compatible document object of the data returned from the server | ||||
status | Numeric status code returned by the server, such as 404 for “Not Found” or 200 for “OK” | ||||
statusText | String message accompanying the status code. |
Pham Cong Dinh
Golden Key Language Center
——————————–
References
1. Effective Ajax Workshop Documentation, August 2005 (Jim Halberg and Rob Sanheim)
2. HTTP Status Codes: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
3. DOM: http://www.w3.org/DOM/