Ajax applications should send and receive as little information as possible to and from the server. In short, Ajax can minimize the amount of traffic between the client and the server.
Asynchronous means that the processing will continue
The most common status codes are:
200 (OK): The resource was found and all is well.
304 (NOT MODIFIED): The resource has not been modified since the last request. This is used most often for browser cache mechanisms.
401 (UNAUTHORIZED): The client is not authorized to access the resource. Often, this will cause the browser to ask for a user name and password to log in to the server.
403 (FORBIDDEN): The client failed to gain authorization. This typically happens if you fail to log in with a correct user name and password after a 401.
404 (NOT FOUND): The resource does not exist at the given location.
Advantage :
It is efficient: only a part of the web page that needs to be modified is being modified. With traditional server-side scripting you send the entire new page to the browser.
It is lightweight: only small amounts of data (in the XML form) are being exchanged through the Internet, making your web applications very fast.
Creating an XMLHttpRequest Object
The XMLHttpRequest object is what you use to give Javascript the ability to request information from the server.
Modern browsers have a predefined class called XMLHttpRequest, that we can use to define our object directly.If not then we need to create createXMLHttp() by checking browser.
var ajaxObj = createXMLHttp();
Opening a Request
Once we have our request object defined the next step is to use it to connect to the server side processing that will retrieve the required information for us.
var url = 'myrequest.php';
ajaxObj.open("GET", url, true); where The third parameter defines whether the call will by asynchronous (true) or synchronous (false).
Response Event Handler
With our AJAX object created and opened, the next step is to define the event handler that will process the response when it comes.
XMLHttpRequest object has a property called readyState that contains one of several values depending on the current status of the request. An associated event handler called onreadystatechange allows us to attach processing that will be run whenever the current status in the readyState field is changed.
ajaxObj.onreadystatechange = function() {
ajaxObj.processRequest();}
processRequest : actually perform the processing that we want when the readyState changes. The readyState field actually has five possible values although not all values are actually set by all browsers. These values are:
0 (uninitialized) - we have created our AJAX object but haven't opened it yet.
1 (loading) - we have called open but haven't yet sent the request.
2 (loaded) - we have sent the request.
3 (interactive) - a partial response has been received.
4 (complete) - a complete response has been received and the connection has been closed.
ajaxObj.processRequest = function() {
if (this.readyState == 4) {
// got response
}
}
Send the Request
The final step before control passes to the server is to send the request.
ajaxObj.send(null);
Passing Parameters
There are several different ways of passing information to the server to tell it what the request is for.
var myform = document.forms[0];
var reqBody = getRequestBody(myform);
ajaxObj.send(reqBody);
Success or Failure
With the sending of the request taken care of we now return to the response event
handler and add the code needed to test if the request worked.
ajaxObj.processRequest = function() {
if (this.readyState == 4) {
if (this.status != 200) {
alert('Error : Status '+this.status+' returned.');
} else {
// got response
}
}
}
Response Type
Having determined that our request was successful we now look at how we can test what type of response we got back - XML or plain text.
else {
var cType = this.getResponseHeader("Content-Type");
if (cType == 'text/xml') {
// XML response
} else if (cType == 'text/plain') {
// plain text response
} else {
alert('unknown content type');
}
responseText and responseXML
Depending on the content type the response is returned in one of two different properties.
Setting Response Type
The server side processing determines the content type of the response.
Javascript Object Notation
The obvious format to use for the response is JSON (since it is both more compact than XML and its relationship to Javascript makes it easier to use).
var respObj = JSON.parse(response);
Parsing XML
var xmlDoc = request.responseXML;
var priceArray = xmlDoc.getElementsByTagName('price');
The responseText field is always returned with a copy of the response so why is there also a responseXML field that gets returned as well but only if the response is XML? Well the responseXML field has already parsed the XML that is in the response for us making it much easier to access the information from Javascript.
Aborting AJAX
Since we are using an asynchronous link to the server our visitor could always change their mind about what they want before it finishes updating. By aborting the prior request we avoid problems.
ajaxObj.abort();
Multiple Requests
When you want to be able to submit multiple requests to the server without aborting prior requests you need to create multiple request objects.
ajaxObj = XMLHttp();
ajaxObj2 = XMLHttp();
Caching of Requests
Some browsers will just return the cached value when you make a second request to the server that looks the same as the first. There are two ways to resolve this to force the browser to pass all of your Ajax requests to the server.
url = url+'?dummy='+ new Date().getTime();
header('Cache-Control: no-cache');
No comments:
Post a Comment