Implementing AJAX In ASP.NET Using XMLHttpRequest Object

Introduction
 
These days most of the web applications are using AJAX concept to create better and more responsive applications. AJAX reduces the traffic between client and server and also response time faster which increases performance of application.
 
Main objective of the article is "How can we implement AJAX in ASP.NET with raw JavaScript code without using any third party library". And also we will discuss how AJAX works internally.
 
What is AJAX
 
AJAX stands for Asynchronous JavaScript And XML. AJAX is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS, and Java Script.
 
Ajax is full featured with Document Object Model (DOM), CSS for presentation and JavaScript for dynamic content display.
Google Maps is the most impressive and obvious example, other powerful, popular scripts such as the vBulletin forum software has also incorporated AJAX into their latest version.
 
Advantages of AJAX
 
Reduce the traffic travels between the client and the server. Response time is faster so increases performance and speed. You can use JSON (JavaScript Object Notation) which is alternative to XML. JSON is key value pair and works like an array. You can use Firefox browser with an add-on called as Firebug to debug all Ajax calls. Ready Open source JavaScript libraries available for use – JQuery, Prototype, Scriptaculous, etc.
 
AJAX communicates over HTTP Protocol.
 
It makes possible to create better and more responsive websites and web applications. AJAX is a web browser technology independent of web server software. It works asynchronously in back end.
 
How AJAX works
 
AJAX communicates with the web server using XMLHttpRequest object. The following diagram illustrates how AJAX communicates between Client and Server.
 

                                             Figure 1: How AJAX works internally
 
Let’s describe each numbers (1,2,3) mentioned in figure:
  1. User sends a request from the UI layer (Presenation) and JavaScript call goes to XMLHttpRequest object.
  2. HTTP Request is sent to the server by XMLHttpRequest object.
  3. Web Server interacts with the database through application server like ASP, JSP, and PHP etc.
  4. Data is retrieved from Data Store and return back to Web Server.
  5. Server sends XML data or JSON data to the XMLHttpRequest callback function.
  6. Client receives data from server and displays using HTML, CSS data on the browser.
What is XMLHttpRequest (XHR)
 
It is an API available in all modern browsers to support HTTP and HTTPS services. It helps to send request to server and get response back from server.
 
AJAX takes advantage of an object built into all modern browsers—-the XMLHttpRequest object—to send and receive HTTP requests and responses. An HTTP request sent via the XMLHttpRequest object does not require the page to have or post a <form> element. The 'A' in AJAX stands for "asynchronous," which means that the XMLHttpRequest object send() method returns immediately, letting the browser processing of other HTML/JavaScript on the Web page continue while the server processes the HTTP request and sends the response. While asynchronous requests are the default, you can optionally send synchronous requests, which halts other Web page processing until the page receives the servers response. Microsoft introduced the XMLHttpRequest object as an ActiveX object in Internet Explorer (IE) 5. Other browser manufacturers, recognizing the object's utility, implemented the XMLHttpRequest object in their browsers, but as a native JavaScript object rather than as an ActiveX object.
 
XHR contains the following methods and properties:
 
Methods
 
abort()
 
It cancels the current request.
 
getResponseHeader()
 
It returns all HTTP headers as string format. HTTP headers like Accept, Accept-Encoding, Cookie, Content-Type, Access-Control-Allow-Origin etc returns using this method.
 
open():
 
It uses to define type request with parameters. It has the following overloaded methods:
 
open(HTTPmethod, URL )
open (HTTPmethod, URL, IsAsync)
open(HTTPmethod, URL, IsAsync,UserName)
open(HTTPmethod, URL, IsAsync, UserName, Password)
 
HTTPmethod: Type of HTTP method like GET, POST DELETE.

URL
: URL of server to where request will send.

IsAsync
: It is a Boolean value (true or false) to define the request is asynchronous or not. Means if it is true then it will wait for response and if it is false then it will not wait server response – it will just next line script. It is recommended to use async=true.
 
UserName: It sets username to send server.
 
Password: It sets password to send server. Username and Password uses to make the request more secure.
 
send()It sends the request to server to perform operation.
 
sendRequestHeader()It appends label/pair value to HTTP headers which needs to send server. Here's the syntax,
setRequestHeader(label, value)
 
Properties
 
onreadystatechanged: It is an event handler which fires when any state of request (defined below) is changed.
 
readyState: This property defines current state of XMLHttpRequest object. It holds 5 values 0,1,2,3,4
 
0: It indicates request is not initialized. It occurs after create object XMLHttpRequest and before open() call.
1: It indicates request is set up. It occurs after open() call and before send() call.
2: It indicates request has been sent. It occurs after send() is called.
3: It indicated browser established a communication with server but server yet to finish the request.
4: It indicates request has been completed and also response received from server.
 
responseText: It returns response as text format.
 
responseXML: It returns response as XML. We need to parse the XML data and read data from it.
 
status: It returns status as number like 404 for “Not Found”, 200 for “OK”, “500” for “Internal server error”.
 
statusText: It returns status as text format like “Not Found”, “OK”, “Internal server error”, etc.
 
Implement AJAX using XMLHttpRequest object 
 
1. Using GET method
 
Firstly, we need to create an object of XMLHttpRequest. Before we create, it needs to check browser type (IE or FF or Chrome) because earlier versions in IE doesn’t support XMLHttpRequest object – it supported only “ActivexObject”. Once object is created, it needs to set onreadystatechanged property to object of XMLHttpRequest. Then we will call send() method for sending request to server.
 
Firstly, we will discuss how can we implement in Webforms and then we will discuss same concept in MVC.

In Web Forms: We have an aspx page called “XMLHttpRequest.aspx” and we will implement AJAX concept with GET method. Here is the complete code for ASPX page:
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="XMLHttpRequest.aspx.cs" Inherits="SampleProject.XMLHttpRequest" %>    
  2.     
  3. <!DOCTYPE html>    
  4.     
  5. <html xmlns="http://www.w3.org/1999/xhtml">    
  6. <head id="Head1" runat="server">    
  7.     <title>XMLHttpRequest Demo</title>    
  8.     <script type="text/javascript">    
  9.     
  10.         function SendAjaxGET() {    
  11.             var xmlHttp;    
  12.             //Let us create the XML http object    
  13.             xmlHttp = null;    
  14.     
  15.             if (window.XMLHttpRequest) {    
  16.                 //for new browsers    
  17.                 xmlHttp = new XMLHttpRequest();    
  18.             }    
  19.             else if (window.ActiveXObject) {    
  20.                 var strName = "Msxml2.XMLHTTP"    
  21.                 if (navigator.appVersion.indexOf("MSIE 5.5") >= 0) {    
  22.                     strName = "Microsoft.XMLHTTP"    
  23.                 }    
  24.                 try {    
  25.                     xmlHttp = new ActiveXObject(strName);    
  26.                 }    
  27.                 catch (e) {    
  28.                     alert("Error. Scripting for ActiveX might be disabled")    
  29.                     return false;    
  30.                 }    
  31.             }    
  32.     
  33.             if (xmlHttp != null) {    
  34.                 //Handle the response of this async request we just made(subscribe to callback)    
  35.                 var userName = "manasm using GET";    
  36.     
  37.                 xmlHttp.onreadystatechange = function () {    
  38.                     alert(xmlHttp.readyState);    
  39.                     if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {    
  40.                         alert(xmlHttp.responseText);    
  41.                     }    
  42.                 }    
  43.     
  44.                 //Pass the value to a web page on server as query string using XMLHttpObject.    
  45.                 xmlHttp.open("GET""XMLHttpRequest.aspx?userName=" + userName, true);    
  46.                 xmlHttp.send();    
  47.             }    
  48.         }    
  49.     </script>    
  50. </head>    
  51. <body>    
  52.     <form id="form1" runat="server">    
  53.         <div>    
  54.             <button type="button" onclick="ShowCurrentTime()">Click Me to Send Ajax(GET) Request</button>    
  55.         </div>    
  56.     </form>    
  57. </body>    
  58. </html>    
In preceding code, it create XMLHttpRequest object and sent it to server. This request injects one parameter called userName with the object.
 
Next in code-behind page, Page_Load()method, we need to write code to retrieve data from request and send response back to client. Request.QueryString() is used to retrieve data(userName parameter) from request. Here is the complete code:
  1. protected void Page_Load(object sender, EventArgs e)    
  2. {    
  3.     if (IsPostBack == false)    
  4.     {    
  5.         // For GET Method    
  6.         if (Request.QueryString["userName"] != null)    
  7.         {    
  8.             Response.Write(Request.QueryString["userName"]);    
  9.             Response.End();  
  10.         }    
  11.     }    
  12. }    
After executing preceding code, it writes querystring value in current response and same value displays through alert message.
 
In MVC

Now we will implement the same AJAX concept in MVC application. JavaScript code is mostly same as webform application. Only change in URL of XMLHttpRequest object and controller action.
 
In View(Index.cshtml):

In view page we just add one button and click of button send AJAX request to server. Just make change in URL attribute of open() – we need to set as "Controller/Action" method. Here is the code: 
  1. <button type="button" onclick="SendAjaxGET()">Click Me to Send Ajax(GET) Request</button>    
  2.     
  3. <script>    
  4.     function SendAjaxGET() {    
  5.         var xmlHttp;    
  6.         //Let us create the XML http object    
  7.         xmlHttp = null;    
  8.     
  9.         if (window.XMLHttpRequest) {    
  10.             //for new browsers    
  11.             xmlHttp = new XMLHttpRequest();    
  12.         }    
  13.         else if (window.ActiveXObject) {    
  14.             //for old ones    
  15.             //xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");    
  16.             var strName = "Msxml2.XMLHTTP"    
  17.             if (navigator.appVersion.indexOf("MSIE 5.5") >= 0) {    
  18.                 strName = "Microsoft.XMLHTTP"    
  19.             }    
  20.             try {    
  21.                 xmlHttp = new ActiveXObject(strName);    
  22.             }    
  23.             catch (e) {    
  24.                 alert("Error. Scripting for ActiveX might be disabled")    
  25.                 return false;    
  26.             }    
  27.         }    
  28.     
  29.         if (xmlHttp != null) {    
  30.             xmlHttp.onreadystatechange = function () {    
  31.                 alert(xmlHttp.readyState);    
  32.                 if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {    
  33.                     alert(xmlHttp.responseText);    
  34.                 }    
  35.             }    
  36.     
  37.             //Pass the value to a web page on server as query string using XMLHttpObject.    
  38.             xmlHttp.open("GET""Home/MyAjaxGET?userName=manasm"true);    
  39.             xmlHttp.send();    
  40.         }    
  41.     }    
  42. <script>    
In Controller: In controller page, Request.QueryString() used to retrieve data (userName querystring value) from request. Here's the code,
  1. public ActionResult MyAjaxGET()  
  2. {  
  3.     string temp = Request.QueryString["userName"];  
  4.   
  5.         // Perform your operation  
  6.   
  7.     return Json(temp, JsonRequestBehavior.AllowGet);  
  8. }  
After executing above code, it returns json data (userName querystring value) back to client and displays alert message as "manasm".
 
2. Using POST method
 
In Web Form: Here is the code for aspx page(XMLHttpRequest.aspx),
  1. <button type="button" onclick="SendAjaxPOST()">Click Me to Send Ajax(POST) Request</button>  
  2.   
  3. <script>  
  4. function SendAjaxPOST() {  
  5.         var xmlHttp;  
  6.         //Let us create the XML http object  
  7.         xmlHttp = null;  
  8.   
  9.         if (window.XMLHttpRequest) {  
  10.             //for new browsers  
  11.             xmlHttp = new XMLHttpRequest();  
  12.         }  
  13.         else if (window.ActiveXObject) {  
  14.             var strName = "Msxml2.XMLHTTP"  
  15.             if (navigator.appVersion.indexOf("MSIE 5.5") >= 0) {  
  16.                 strName = "Microsoft.XMLHTTP"  
  17.             }  
  18.             try {  
  19.                 xmlHttp = new ActiveXObject(strName);  
  20.             }  
  21.             catch (e) {  
  22.                 alert("Error. Scripting for ActiveX might be disabled")  
  23.                 return false;  
  24.             }  
  25.         }  
  26.   
  27.         if (xmlHttp != null) {  
  28.             //Handle the response of this async request we just made(subscribe to callback)  
  29.             //xmlHttp.onreadystatechange = state_Change;  
  30.             var userName = "manasm";  
  31.   
  32.             xmlHttp.onreadystatechange = function () {  
  33.                 alert(xmlHttp.readyState);  
  34.                 if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {  
  35.                     alert(xmlHttp.responseText);  
  36.                 }  
  37.             }  
  38.   
  39.             //Pass the value to a web page on server as query string using XMLHttpObject.  
  40.             xmlHttp.open("POST""XMLHttpRequest.aspx"true);  
  41.             xmlHttp.setRequestHeader("Content-type""application/x-www-form-urlencoded");  

  42.             xmlHttp.send("userName=manasm&lname=mohapatra");  
  43.         }  
  44.     }  
  45. </script>  
In preceding code, it is almost similar GET method (described earlier) except URL and parameter. Here we pass parameters in Form object(before it was query string in GET method).
 
In code-behind(XMLHttpRequest.aspx.cs) it fetches value through Request.Form["userName"] and sends back to client.
  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     if (IsPostBack == false)  
  4.     {  
  5.         // For POST method  
  6.         if (Request.Form["userName"] != null)  
  7.         {  
  8.             Response.Write(Request.Form["userName"]);  
  9.             Response.End();  
  10.         }  
  11.     }  
  12. }  
Now we will see how we can implement the same in MVC application. Here is the complete code for view page:
 
View page(index.cshtml)
  1. <button type="button" onclick="SendAjaxPOST()">Click Me to Send Ajax(POST) Request</button>  
  2.   
  3. <script>  
  4. function SendAjaxPOST() {  
  5.         var xmlHttp;  
  6.         //Let us create the XML http object  
  7.         xmlHttp = null;  
  8.   
  9.         if (window.XMLHttpRequest) {  
  10.             //for new browsers  
  11.             xmlHttp = new XMLHttpRequest();  
  12.         }  
  13.         else if (window.ActiveXObject) {  
  14.             //for old ones  
  15.             //xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");  
  16.             var strName = "Msxml2.XMLHTTP"  
  17.             if (navigator.appVersion.indexOf("MSIE 5.5") >= 0) {  
  18.                 strName = "Microsoft.XMLHTTP"  
  19.             }  
  20.             try {  
  21.                 xmlHttp = new ActiveXObject(strName);  
  22.             }  
  23.             catch (e) {  
  24.                 alert("Error. Scripting for ActiveX might be disabled")  
  25.                 return false;  
  26.             }  
  27.         }  
  28.   
  29.         if (xmlHttp != null) {  
  30.             //Handle the response of this async request we just made(subscribe to callback)  
  31.             //xmlHttp.onreadystatechange = state_Change;  
  32.             var userName = "manasm";  
  33.   
  34.             xmlHttp.onreadystatechange = function () {  
  35.                 alert(xmlHttp.readyState);  
  36.                 if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {  
  37.                     alert(xmlHttp.responseText);  
  38.                 }  
  39.             }  
  40.   
  41.             //Pass the value to a web page on server as query string using XMLHttpObject.  
  42.             xmlHttp.open("POST""Home/MyAjaxPOST"true);  
  43.             //var parameters = "userName=XXX";  
  44.             xmlHttp.setRequestHeader("Content-type""application/x-www-form-urlencoded");  
  45.             xmlHttp.send("userName=manasm&lname=mohaptra");  
  46.         }  
  47.     }  
  48. </script>  
Controller
  1. [HttpPost]  
  2. public ActionResult MyAjaxPOST()  
  3. {  
  4.     ViewBag.Message = "Your app description page.";  
  5.     string temp = Request.Form["userName"];  
  6.   
  7.     return Json(temp);   
  8. }  
In preceding code, it retrieves value from Request.Form["Key"] object and returns same userName value as JSON data to client.
 
Conclusion
 
In this article we discussed what is AJAX and its advantages. Secondly, we discussed how it can implement through raw JavaScript using XMLHttpRequest object. We can implement the same AJAX through jQuery and other JavaScript library. jQuery AJAX internally creates XMLHttpRequest (XHR) object and do whatever XHR is doing here. So don’t confuse. If you are using jQuery and other library then use AJAX concept as per library like $.ajax() for jQuery. If you want to implement with raw JavaScript then use XMLHttpRequest object. Main objective of this article is how AJAX works internally (what object it creates and method it uses).


Similar Articles