AJAX



AJAX = Asynchronous JavaScript and XML.
AJAX is the art of exchanging data with a server, and updating parts of a web page - without reloading the whole page. i.e. AJAX allows you to send only important information to the server not the entire page. So it is fast.
There are many different way to perform Ajax call but now I am focusing only these two way :-
1)simple Ajax with JavaScript only and
2) Jquery Ajax call with gson API.
Properties of XMLHttpRequest object
Property
Description
onReadyStateChange
It is called whenever readystate attribute changes. It must not be used with synchronous requests.
readyState
represents the state of the request. It ranges from 0 to 4.0 UNOPENED open() is not called.
1 OPENED open is called but send() is not called.
2 HEADERS_RECEIVED send() is called, and headers and status are available.
3 LOADING Downloading data; responseText holds the data.
4 DONE The operation is completed fully.
reponseText
returns response as text.
responseXML
returns response as XML

Methods of XMLHttpRequest object
Method
Description
void open(method, URL)
opens the request specifying get or post method and url.
void open(method, URL, async)
same as above but specifies asynchronous or not.
void open(method, URL, async, username, password)
same as above but specifies username and password.
void send()
sends get request.
void send(string)
send post request.
setRequestHeader(header,value)
it adds request headers.

How AJAX works ?
AJAX communicates with the server using XMLHttpRequest object.
Step by Step Ajax Flow:-
1)User sends a request from the UI and a javascript call goes to XMLHttpRequest object.
2)HTTP Request is sent to the server by XMLHttpRequest object.
3)Server interacts with the database using JSP, Servlet, Controller etc.
4)Data is retrieved.
5)Server sends XML data or JSON data to the XMLHttpRequest callback function.
6)HTML and CSS data is displayed on the browser.

Example:-
<script type="text/javascript">
var xmlhttp;
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
                xmlhttp.open("GET", "/interstitialAdd", true);
    xmlhttp.send();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 ) {
           if(xmlhttp.status == 200){                                                
               ocument.getElementById("myDiv").innerHTML = xmlhttp.responseText;
           }
           else if(xmlhttp.status == 400) {
              alert('There was an error 400')
           }
           else {
              // alert('something else other than 200 was returned')
           }
        }
    }   
</script>
Jquery Ajax
JQuery is a great tool which provides a rich set of AJAX methods to develop next generation web application.
The JQuery’s $.ajax() function is used to perform an asynchronous HTTP request.
For this you have include JQuery JavaScript file in you JSP or html page.
<script type="text/javascript"  src="/jquery/jquery-1.3.2.min.js"></script>
There are a lot of different options you can specify in $.ajax()  according to your need:-
accepts: The content type sent in the request header that tells the server what kind of response it will accept in return
async: Set this options to false to perform a synchronous request
beforeSend: A pre-request callback function that can be used to modify the jqXHR object before it is sent
cache: Set this options to false to force requested pages not to be cached by the browser
complete: A function to be called when the request finishes (after success and error callbacks are executed)
contents: An object that determines how the library will parse the response
contentType: The content type of the data sent to the server
context: An object to use as the context (this) of all Ajax-related callbacks
converters: An object containing dataType-to-dataType converters
crossDomain: Set this property to true to force a cross-domain request (such as JSONP) on the same domain
dataFilter: A function to be used to handle the raw response data of XMLHttpRequest
global: Whether to trigger global Ajax event handlers for this request
headers: An object of additional headers to send to the server
ifModified: Set this option to true if you want to force the request to be successful only if the response has changed since the last request
isLocal: Set this option to true if you want to force jQuery to recognize the current environment as “local”
jsonp: A string to override the callback function name in a JSONP request
jsonpCallback: Specifies the callback function name for a JSONP request
mimeType: A string that specifies the mime type to override the XHR mime type
password: A password to be used with XMLHttpRequest in response to an HTTP access authentication request
processData : Set this option to false if you don’t want that the data passed in to the data option (if not a string already) will be processed and transformed into a query string
scriptCharset: Sets the charset attribute on the script tag used in the request but only applies when the “script” transport is used
timeout: A number that specifies a timeout (in milliseconds) for the request
traditional: Set this to true if you wish to use the traditional style of param serialization
username: A username to be used with XMLHttpRequest in response to an HTTP access authentication request
xhr: A callback for creating the XMLHttpRequest object
xhrFields: An object to set on the native XHR object
Important and frequently used
statusCode: An object of numeric HTTP codes and functions to be called when the response has the corresponding code
success: A function to be called if the request succeeds
error: A function to be called if the request fails
dataType: The type of data expected back from the server
data: The data to send to the server when performing the Ajax request
type: The type of request to make, which can be either “POST” or “GET”
url: A string containing the URL to which the request is sent

Example:-
function ajaxResendOTP() {
      $.ajax({
        url: "/ajaxResendOTP",
        type: "post",
        dataType: "html",
        error: function() {
            jContent.html("<p>Page Not Found!!</p>")
        },
        beforeSend: function() {},
        complete: function() {},
        success: function(responseData) {
             document.getElementById("myDiv").innerHTML="responseData";
        }
    })
}

Note :-
1) Download jquery and include in jsp or html page
2) Download gson jar and placed in you web application lib
Like gson.jar

No comments:

Post a Comment