Wednesday, June 5, 2013

AJAX - First Sample

AJAX, a.k.a Asynchronous JavaScript and XML. According to the name, we can feel it is not a new technology, but something JavaScript and XML related. AJAX is actually a new way of exchanging data using current standards. AJAX allows user to request only necessary data from the server and update the data on page, so we don't have to reload the whole page.

So let us see a simplest sample
    

    AJAX Sample




Several interesting things in above code.

XMLHttpRequest
It is used to send HTTP and HTTPS requests to the server and load response data. The data could be received from the server as JSON, XML, HTML or plain text. In our example, it is plain text.
xmlhttp.open
The requests must be initialized through the open method. It has five parameters in total (Method, URL, Asynchronous, UserName, Password) and only the first two are required. Supported methods could be GET, POST, HEAD, PUT, DELETE and OPTIONS. Asynchronous has two Boolean values, and true is the default one. False will block execution of the current script until the request has been completed, thus not invoking the onreadystatechange event listener.
xmlhttp.send
Send the request and you can specify a string data for and only for POST request.
xmlhttp.onreadystatechange
It is a event listener and will be automatically invoked when readyState property of the XMLHttpRequest object is changed.
xmlhttp.readyState
equals 1 after open has been invoked successfully
equals 2 after send has been invoked and response head has been received
equals 3 after response starts to load
equals 4 after response has finished loading
If you would like to see how the readyState is changed, try below code
    
if (xmlhttp.readyState == 1) {
    document.getElementById("result").innerHTML = xmlhttp.readyState;
} else if (xmlhttp.readyState == 2) {
    var state = xmlhttp.readyState;
    setTimeout(function() {document.getElementById("result").innerHTML = state}, 2000);
} else if (xmlhttp.readyState == 3) {
    var state = xmlhttp.readyState;
    setTimeout(function() {document.getElementById("result").innerHTML = state}, 4000);
} else if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    var state = xmlhttp.readyState;
    setTimeout(function() {document.getElementById("result").innerHTML = state}, 6000);
    setTimeout(function() {document.getElementById("result").innerHTML = xmlhttp.responseText;}, 8000);
} else {
    document.getElementById("result").innerHTML = "Failed to load.";
}

No comments:

Post a Comment