Ajax Workflow

With traditional HTML and JavaScript, to get some data from the server side, it was necessary to make a form submission. With each submission the entire form was being reloaded. So it was loading an entirely new page and that was making performance slow.

By 2003, all the major browsers adopted the XMLHttpRequest (XHR) object, that allowed browsers to communicate with the server directly without a page reload.

The JavaScript object “XMLHttpRequest” is actually part of AJAX technology. Using the XMLHttpRequest API, JavaScript can directly interact with the server. The user can make a request to the server with a HTTP Get Response from the server and modify the required portion only (without a form submission/reload). But, various browsers implement it differently. For example Internet Explorer uses an ActiveXObject whereas other modern browsers use the built-in “XMLHttpRequest” JavaScript object.

So it's an overhead for developers to make implementation of XMLHttpRequest universal. To create an object that can call Server-side functionality directly we need to consider other browsers like:

  1. function CreateAsyncObject()   
  2. {  
  3.     var ObjXmlHttp;  
  4.     try  
  5.     {  
  6.          ObjXmlHttp = new XMLHttpRequest();  
  7.     }  
  8.     catch(Exception OuterEx)  
  9.     {  
  10.         try  
  11.         {  
  12.              ObjXmlHttp = ActiveXObject(“Msxml2.XMLHTTP”);  
  13.         }  
  14.         catch(Exception Ex)  
  15.         {  
  16.             try  
  17.             {  
  18.                 ObjXmlHttp = ActiveXObject(“Microsoft.XMLHTTP”);  
  19.             }  
  20.             catch(Exception ExInner)  
  21.             {  
  22.                 alert(“Your browser doesn't support XMLHttpRequest.”);  
  23.             }  
  24.         }  
  25.     }  
  26. }  
Then we need to open this object with the required parameters and send it to the server like:
  1. ObjXmlHttp.open(“<GET/POST>”, “<Server side url>”, <true/false>);  
The last parameter indicates whether the request is to be handled asynchronously.
  1. ObjXmlHttp.send(null);   
Properties of XMLHttpRequest
  • ReadyState: It has a value from 0 to 4.

    1. The XMLHttpRequest object is created, but open() has not been called.
    2. open () is called, but not send().
    3. send() has been called
    4. The browser has established a connection with the server but the server hasn't processed the response.
    5. The response data has been completely received from the server.

  • Onreadystatechange: This is an event handler for the change in readyState

  • responseText: Server response as a string

  • responseXML: Response as XML.

  • status: status of the HTTP request(200, 404 and so on)

  • statusText: status as a message (“OK”, “Not found” and so on)

A complete request using XMLHttpRequest will be as follows:

  1. <input type= “text” onkeyup = “GetName()”>  
  2. <div id= “divResult”></div>  
  3.   
  4. function GetName()   
  5. {  
  6.     var ObjXmlHttp;  
  7.     try  
  8.     {  
  9.          ObjXmlHttp = new XMLHttpRequest();  
  10.     }  
  11.     catch(Exception OuterEx)  
  12.     {  
  13.         try  
  14.         {  
  15.              ObjXmlHttp = ActiveXObject(“Msxml2.XMLHTTP”);  
  16.         }  
  17.         catch(Exception Ex)  
  18.         {  
  19.             try  
  20.             {  
  21.                 ObjXmlHttp = ActiveXObject(“Microsoft.XMLHTTP”);  
  22.             }  
  23.             catch(Exception ExInner)  
  24.             {  
  25.                 alert(“Your browser doesn't support XMLHttpRequest.”);  
  26.             }  
  27.         }  
  28.     }  
  29.     ObjXmlHttp.open(“GET”, “GetName.aspx”, true);  
  30.      ObjXmlHttp.onreadystatechange(function(){  
  31.         if(readyState == 4)  
  32.         {  
  33.              divResult.innerHTML =  ObjXmlHttp.responseText;  
  34.         }  
  35.     });  
  36. }  
jQuery-Ajax

jQuery provides Ajax support that removes all the overhead of creating objects (considering various browsers), handling a “readystatechange” event, checking readyState and so on. By some full-featured method like $.ajax() and some convenience methods like $.get(), $.post() and so on.
  • $.get()

    It makes a get request to the provided URL.

  • $.post()

    It makes a post request to the provided URL.

  • $.ajax()

    This jQuery method takes a configuration object having all instructions, that jQuery requires to complete the request.

There are many $.ajax() Options available. Some of the most common properties are:

Option Description Default value
async If the request should be served asynchronously (true)
url URL to request. This is the only required value to make an Ajax call  
contentType Type of content query is ed to the server application/x-www-form-urlencoded;charset=UTF-8
data Data query is ed to the server  
dataType Type of data jQuery is expecting from server MIME type of response
success Success callback  
error Error callback  
complete Code to execute irrespective of success/failure  
crossDomain It indicates if request is to/from cross-domain (false)

NOTE: If you are not sure about ContentType and dataType, just don't mention them in the configuration of a jQuery Ajax call, It'll take default values that will satisfy most of the types.

  1. $.ajax({  
  2.                type: "POST",  
  3.                url:"http://localhost/WebServiceForBlog/MyService.asmx/SumOfNums",  
  4.                data: "First=" + FirstNum + "&Second=" + SecondNum,   
  5.                contentType: "application/x-www-form-urlencoded;charset=UTF-8"    
  6.                dataType: "text",  
  7.                crossDomain: true,  
  8.                success: function (data) {  
  9.                    $('#divSum1').html(data);  
  10.                }  
  11.         error: function(data)  
  12.         {alert("Error");}  
  13.            });  
Let's discuss one of the most commonly used callback functions.

error
  • function(jqXHR, textStatus, errorThrown).
  • jqXHR: A string describing the type of error that has occurred and an exception object (if occurred).
  • TextStatus: request status like null, "timeout", "error", "abort", and "parsererror".
  • ErrorThrown: Textual portion of the HTTP status, such as "Not Found".

Success

  • function(data, textStatus, jqXHR).
  • data: data returned from server.
  • textStatus: string decribing the status.
  • JqXHR: success setting.

These jQuery methods use the XMLHttpRequest API internally for calling server-side functionalities directly.

By default, Ajax doesn't support cross-domain calls since it violates “Same origin policy”. JSONP (JSON with padding) that uses Cross-Origin Resource Sharing can be used for cross-domain calls.

Up Next
    Ebook Download
    View all
    Learn
    View all