Ajax - Technical Introduction
1) Getting the HTTP Request Object:
We have already discussed that Ajax uses JavaScript to make a request from the server.
For this we need an object of such class, which can provide this functionality. For this we have to
select any one of the following two classes depending on the browser:
1. ActiveXObject (For Internet Explorer browser) or
2. XMLHttpRequest (For Mozilla, Safari etc.)
To write browser independent code, you can follow the simplified code snippet below:
var xmlHttp;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
var xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) { // IE
var xmlHttp = new ActiveXObject(“Microsoft.XMLHTTP”);
}
2) Deciding the method to be called after receiving the response from the server:
The next step is to decide which JavaScript function is to be called after receiving the response from
the server. In this method you can write the code to process and manipulate the data received from
the server. There are two ways to set the function for this purpose:
i) Set the property “onreadystatechange” of the Http request object to the name
of that JavaScript function
For example, you want JavaScript function “myMethod” to be executed after receiving the response
from the server. Then you have to write the code like below:
XmlHttp.onreadystatechange = myMethod; // No bracket after the function.
Remember, this line is not for calling the method “myMethod” but only for assigning a reference to
the function, which will be called after receiving the response from the server.
ii) Using anonymous function:
Write the code of the function just at the same place instead of referencing the name of the
function. For example,
xmlHttp.onreadystatechange = function() {
…………………..
// Do something with the response data
…………………..
}
3) Making an HTTP Request
Actually we have not made any request in the previous step. We decided only which method would
process the response data after receiving the data from the server. So now it’s turn to send the
|