Friday, March 28, 2008

All About AJAX

AJAX (ASynchronous JavaScript And XML): The main purpose of Ajax is to provide a simple and standard means for a web page to communicate with the server without a complete page refresh. Synchronous calls force the browser to wait for a response from the server before continuing. This leaves the user unable to interact with the browser until the response is complete. Asynchronous requests allow the browser to continue to process code while waiting for a response. Steps may be defined as :
1. Get whatever data you need from the Web form.
2. Build the URL to connect to.
3. Open a connection to the server.
4. Set up a function for the server to run when it's done.
5. Send the request.

Making GET request :
xmlhttp.open("GET","Demo.jsp",true);
xmlhttp.send(null);

Making POST request :
xmlhttp.open("POST","Demo.jsp",true);
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
xmlhttp.send("FirstName=Nat&LastName=Dunn");

=> XMLHttpRequest readyState Property :
* 0 (uninitialized)
* 1 (loading)
* 2 (loaded)
* 3 (interactive)
* 4 (complete)

=> XMLHttpRequest Object Properties :
* onreadystatechange : Specifies the callback function to be triggered when the ready state changes.
* readyState : Holds the state of the response.
* responseText : Holds the message body as a string.
* responseXML : Holds the message body as an XML object.
* status : Holds the status code returned from the server (eg. 200:success, 404:page not found)
* statusText : Holds the status text returned from the server.

=> XMLHttpRequest Object Methods :
* abort() : Aborts the xmlhttp request.
* getAllResponseHeaders() : Retrieves the values of all the HTTP headers as a string.
* getResponseHeader(header) : Retrieves the value of the specified HTTP header as a string.
* open(Method,URL,Async) : Initializes the XMLHttpRequest object.
* send(header) : Sends the HTTP request to the server.
* setRequestHeader(header,value) : Specifies the name and value of an HTTP header.

No comments: