Ajax programming techniques

AJAX is one of the most fashionable words in the information technology world and is the technical secret behind major applications in Google, Flickr, GMail, Google Suggest, and Google Maps.Although this name has been around for only a few months, InfoWorld has released a review in May 2005: Ajax is creating a revolution in the web world.

WHAT IS AJAX?

JavaScript, the programming language running on the browser has been so familiar to the web world since Netscape invented it. The development of technology and increasing user demand compels developers to create another technique that allows for more complex tasks. In February 2005, the Internet began spreading Ajax terminology as a new technique for web applications. The resounding success and the strange appeal of Gmail, Google Suggest and Google Maps have made Ajax particularly noticeable.

Ajax stands for Asynchronous JavaScript and XML - a technique that incorporates two powerful JavaScript features that are highly appreciated by developers:

• Sending a request to the server without reloading the page

• Split and work with XML

Ajax applications revolve around a feature called XMLHttpRequest. Mozilla project engineers started supporting this feature in Mozilla 1.0 (and Netscape 7). Apple has also made a similar feature since Safari 1.2.

Ajax is a combination of a variety of technologies that are attracting the attention of industry in recent times. That is:

• Site presentation based on XHTML and CSS, W3C standards, Firefox (Mozilla), Safari (Apple), Opera, Netscape 8.0 (Firefox core) are very well supported;

• Dynamic and interactive expressions using the W3C Document Object Model;

• Data exchange and processing using XML and XSLT, W3C standard;

• Retrieve asymmetric data using XMLHttpRequest;

• Use JavaScript to link things together. JavaScript here is ECMAScript, ECMA standard, not Microsoft JScript.

In traditional web applications, the client sends an HTTP Request to the web server and the web server sends a response containing the information in HTML and CSS. Ajax allows creating an Ajax Engine in the middle of this communication. Then, the request sends resquest and receives the response made by the Ajax Engine. Instead of returning data in HTML and CSS directly to the browser, the web server can return data in XML and Ajax Engine will receive, decompose, and transform into XHTML + CSS for the browser to display. This is done on the client, so reducing the load a lot for the server, and the user feels the processing results are displayed immediately without reloading the page. On the other hand, the combination of web technologies such as CSS and XHTML makes the presentation of website interfaces much better and significantly reduces the amount of page load. These are very practical benefits that Ajax brings.

PROGRAM AJAX

Handling HTTP Request

To send an HTTP Request to the server using JavaScript, you need to create an object of the class that provides this feature. In IE, this class exists as an ActiveX object called XMLHTTP. This object comes from IE 4.0.
httpRequest var = new ActiveXObject ("Microsoft.XMLHTTP");

If MSXML is installed, you can also call:

httpRequest var = new ActiveXObject ("Msxml2.XMLHTTP");

In Mozilla, Firefox, Opera 8.0, Safari and other browsers this class is named XMLHttpRequest. The XMLHttpRequest object is not a W3C standard (the future may be approved by the W3C). 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 ();

Because of this difference, so that 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 on 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 done through the value of window.ActiveXObject. For example:

if (window.ActiveXObject) {

xmlhttp = new ActiveXObject ("Microsoft.XMLHTTP")

}

else {.}

Some versions of the Mozilla browser do not work properly when receiving a response from the server without the header containing the XML mime-type. To fix this problem, you can use the header redefinition method sent by the server in case it is not text / xml.

httpRequest = new XMLHttpRequest ();

httpRequest.overrideMimeType (text / xml);

Next, you need to determine what you want to do after receiving a response from the server. At this stage, you only need to tell the HTTP request object that the JavaScript function will do the response processing. This is done by setting the object's onreadystatechange attribute to the JavaScript function name:

httpRequest.onreadystatechange = nameOfTheFunction;

Note not to use parentheses () after the function name and do not pass parameters to that function. In addition, instead of giving function names, you can use dynamic function definition techniques:

httpRequest.onreadystatechange = function () {

// do the thing

};

After declaring what will happen at the time of 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 call to open () is the HTTP Request - GET method, POST, HEAD or whatever method you want to use and that method needs to be supported by the server. Note that capitalization is in accordance with the HTTP standard, otherwise some browsers such as Firefox may not process the request.

The second parameter is the URL of the page you sent the request to. Due to security settings, you cannot call pages on third-party domains. Note that if you do not call the correct domain name on all pages, you will get a permission denied when calling open ().

The third parameter determines whether the request is asymmetric (asynchronous). If TRUE, then executing the JavaScript function will continue while the server response has not arrived. This is the letter A in AJAX.

The parameter sent to the send () method can be any data you want to send to the server if you use the POST method to send the request. The data will take the form of a query string:

name = value & anothername = othervalue & so = on

The XMLHttpRequest object has a set of shared properties on all supported environments. Below is a list of key properties of this object.

Handling Response Server

Note when sending a request, you provide the name of the JavaScript function designed to handle the response.

httpRequest.onreadystatechange = nameOfTheFunction;

See what this function should do. First, the function needs to check the status of the request. If the status has a value of 4, then your application has received a full response from the server and that is a good sign for you to continue processing it.

if (httpRequest.readyState == 4) {

// no problem occurred and you received the response

} else {

// not ready

}

Next, we need to check the status code of the HTTP server response. All codes can be reviewed at the W3C site. In this article, we are interested in the response 200 (OK).

if (httpRequest.status == 200) {

// response state returns a good sign!

} else {

// have problems receiving and processing requests,

// example 404 (Not Found)

// or 500 (Internal Server Error)

}

After checking the status of the request and the status code of the HTTP response, the processing of the data that the server sends depends on you. You have two options:

• httpRequest.responseText - returns as text string

• httpRequest.responseXML - returns as XMLDocument object and you can browse using JavaScript DOM functions

Example with Text Response

We will build a simple example. JavaScript codes send requests to an HTML page, test.html. This page contains the line "Im a test", then we use alert () to send out the contents of the file.




style = "cursor: pointer; text-decoration: underline"

onclick = "makeRequest (test.html)">





In this example, the user clicks on the "Make a request" link on the browser, which calls the makeRequest () function with a parameter - the name test.html of the HTML file in the same directory. Then the request is made.

Next, you define the alertContents () function which will handle the onreadystatechange case. alertContents () checks whether the response has been received and if OK, it will execute the alert () to send the contents of the test.html file.

For example, with XML Response

The recently surveyed example illustrates how to use the reponseText attribute of the request object. The following example will illustrate the responseXML attribute.

The first thing is to prepare the XML page that will be used for later requests.The following page is named test.xml:

Picture 1 of Ajax programming techniques





Im a test.



In the code line of the example above we just need to replace the request line with:

.

onclick = "makeRequest (test.xml)">

.

Then in alertContents () we need to change the alert line (httpRequest.responseText); with:

var xmldoc = httpRequest.responseXML;

var root_node = xmldoc.getElementsByTagName (root) .item (0);

alert (root_node.firstChild.data);

responseXML retrieves our XMLDocument object and we will use DOM methods to access some of the data contained in the XML page.

Example source code can be downloaded at TGVT website, you can also run directly at http://goldenkey.edu.vn/ajax.

 

onreadystatechange

  

The event handler for an event arises every time a state changes.

  

readyState

  

Status: 0 = uninitialized 1 = loading 2 = loaded 3 = interactive 4 = complete

  

responseText

  

Data as String returns from the server

  

responseXML

  

Document object compatible with DOM of data returned from the server

  

status

  

The numeric status code returned by the server, like 404 for "Not Found" or 200 for "OK"

  

statusText

  

The message String message comes with a status code.

 

Pham Cong Dinh
Golden Key Language Center
--------------------------------
References
1. Workshop document Effective Ajax 8/2005 (Jim Halberg and Rob Sanheim)
2. HTTP status code: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
3. DOM:http://www.w3.org/DOM/