Thursday, August 29, 2013

AJAX Tutorial


AJAX Tutorial

AJAX → Asynchronous JavaScript and XML.

AJAX is a mechanism of exchanging data with a server, and updating parts of a web page, without reloading the whole page.

* AJAX is a technique for creating fast and dynamic web pages.

Examples of applications using AJAX:
   * Google Maps,
   * Gmail,
   * Youtube


Browser
Internet
Server
An event Occurs
* Create an XMLHttpRequest Object
* Send Http Request




-------------------------------------->


* Process HttpRequest

* Create a response and send data back to the browser.
* Process the returned data using javaScript
* Update Page Content

<-------------------------------------

XMLHttpRequest object - to exchange data asynchronously with a server
JavaScript / DOM - to display/interact with the information

The XMLHttpRequest Object -

The XMLHttpRequest object is used to exchange data with the server and update parts of a web page, without reloading the whole page.

Create an XMLHttpRequest Object
All modern browsers have a built-in XMLHttpRequest object.

Syntax : variable = new XMLHttpRequest();
Send a request to a server.
Use the open() and send() methods of the XMLHttpRequest object:

Syntax :
                variable = xmlhttp.open(method,url,async); // e.g. open("GET","ajax-info.txt",true);
                xmlhttp.send();

method : the type of request: GET or POST
url : the location of the file on the server . This can be a any kind of file.
async : true (asynchronous) or false (synchronous)

                send(string) : string, only used for the POST request.


Asynchronous - True | False

Many of the tasks performed on the server are very time consuming.
Before AJAX, this operation could cause the application to hang or stop.
With AJAX, the JavaScript does not have to wait for the server response, it can execute other scripts while waiting for server response and deal with the response when the response ready .

async = true : When using async=true, specify a function to execute when the response is ready in the onreadystatechange event.

xmlhttp.onreadystatechange=function(){
    if(xmlhttp.readyState==4 && xmlhttp.status==200){
       document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
}
xmlhttp.open("GET","ajax-info.txt",true);
xmlhttp.send();

async = false : is not recommended, but for a few small requests this can be ok.

Please note that the JavaScript will NOT continue to execute, until the server response is ready. If the server is busy or slow, the application will hang or stop.

Note: When you use async=false, do NOT write an onreadystatechange function. Just put the code after the send() statement:
    xmlhttp.open("GET","ajax-info.txt",false);
    xmlhttp.send();
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

Server Response -

To get the response from the server, can use the responseText or responseXML property.

responseText : get the response data as a string
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

responseXML : get the response data as XML data

The onreadystatechange event -

The onreadystatechange event is triggered every time the readyState changes.
The readyState property holds the status of the XMLHttpRequest.
 
Three important properties of the XMLHttpRequest object:
 
onreadystatechange : Stores a function (or the name of a function) to be called automatically each time the readyState property changes
readyState : Holds the status of the XMLHttpRequest. Changes from 0 to 4:
                        0: request not initialized
                        1: server connection established
                        2: request received
                        3: processing request
                        4: request finished and response is ready
status 200 : "OK"
                      404: Page not found
*** When readyState is 4 and status is 200, the response is ready.

Note: The onreadystatechange event is triggered five times (0-4), one time for each change in readyState.

Using a Callback Function

A callback function is a function passed as a parameter to another function.
* If you have more than one AJAX tasks, should create ONE standard function for creating the XMLHttpRequest object, and call this for each AJAX task.
* The function call should contain the URL and what to do on onreadystatechange (which is probably different for each call):