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.
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.
AJAX communicates with the web server using XMLHttpRequest object. The following diagram illustrates how AJAX communicates between Client and Server.
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.
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:
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="XMLHttpRequest.aspx.cs" Inherits="SampleProject.XMLHttpRequest" %>
-
- <!DOCTYPE html>
-
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head id="Head1" runat="server">
- <title>XMLHttpRequest Demo</title>
- <script type="text/javascript">
-
- function SendAjaxGET() {
- var xmlHttp;
-
- xmlHttp = null;
-
- if (window.XMLHttpRequest) {
-
- xmlHttp = new XMLHttpRequest();
- }
- else if (window.ActiveXObject) {
- var strName = "Msxml2.XMLHTTP"
- if (navigator.appVersion.indexOf("MSIE 5.5") >= 0) {
- strName = "Microsoft.XMLHTTP"
- }
- try {
- xmlHttp = new ActiveXObject(strName);
- }
- catch (e) {
- alert("Error. Scripting for ActiveX might be disabled")
- return false;
- }
- }
-
- if (xmlHttp != null) {
-
- var userName = "manasm using GET";
-
- xmlHttp.onreadystatechange = function () {
- alert(xmlHttp.readyState);
- if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
- alert(xmlHttp.responseText);
- }
- }
-
-
- xmlHttp.open("GET", "XMLHttpRequest.aspx?userName=" + userName, true);
- xmlHttp.send();
- }
- }
- </script>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <button type="button" onclick="ShowCurrentTime()">Click Me to Send Ajax(GET) Request</button>
- </div>
- </form>
- </body>
- </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:
- protected void Page_Load(object sender, EventArgs e)
- {
- if (IsPostBack == false)
- {
-
- if (Request.QueryString["userName"] != null)
- {
- Response.Write(Request.QueryString["userName"]);
- Response.End();
- }
- }
- }
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:
- <button type="button" onclick="SendAjaxGET()">Click Me to Send Ajax(GET) Request</button>
-
- <script>
- function SendAjaxGET() {
- var xmlHttp;
-
- xmlHttp = null;
-
- if (window.XMLHttpRequest) {
-
- xmlHttp = new XMLHttpRequest();
- }
- else if (window.ActiveXObject) {
-
-
- var strName = "Msxml2.XMLHTTP"
- if (navigator.appVersion.indexOf("MSIE 5.5") >= 0) {
- strName = "Microsoft.XMLHTTP"
- }
- try {
- xmlHttp = new ActiveXObject(strName);
- }
- catch (e) {
- alert("Error. Scripting for ActiveX might be disabled")
- return false;
- }
- }
-
- if (xmlHttp != null) {
- xmlHttp.onreadystatechange = function () {
- alert(xmlHttp.readyState);
- if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
- alert(xmlHttp.responseText);
- }
- }
-
-
- xmlHttp.open("GET", "Home/MyAjaxGET?userName=manasm", true);
- xmlHttp.send();
- }
- }
- <script>
In Controller: In controller page, Request.QueryString() used to retrieve data (userName querystring value) from request. Here's the code,
- public ActionResult MyAjaxGET()
- {
- string temp = Request.QueryString["userName"];
-
- // Perform your operation
-
- return Json(temp, JsonRequestBehavior.AllowGet);
- }
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),
- <button type="button" onclick="SendAjaxPOST()">Click Me to Send Ajax(POST) Request</button>
-
- <script>
- function SendAjaxPOST() {
- var xmlHttp;
-
- xmlHttp = null;
-
- if (window.XMLHttpRequest) {
-
- xmlHttp = new XMLHttpRequest();
- }
- else if (window.ActiveXObject) {
- var strName = "Msxml2.XMLHTTP"
- if (navigator.appVersion.indexOf("MSIE 5.5") >= 0) {
- strName = "Microsoft.XMLHTTP"
- }
- try {
- xmlHttp = new ActiveXObject(strName);
- }
- catch (e) {
- alert("Error. Scripting for ActiveX might be disabled")
- return false;
- }
- }
-
- if (xmlHttp != null) {
-
-
- var userName = "manasm";
-
- xmlHttp.onreadystatechange = function () {
- alert(xmlHttp.readyState);
- if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
- alert(xmlHttp.responseText);
- }
- }
-
-
- xmlHttp.open("POST", "XMLHttpRequest.aspx", true);
- xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
- xmlHttp.send("userName=manasm&lname=mohapatra");
- }
- }
- </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.
- protected void Page_Load(object sender, EventArgs e)
- {
- if (IsPostBack == false)
- {
-
- if (Request.Form["userName"] != null)
- {
- Response.Write(Request.Form["userName"]);
- Response.End();
- }
- }
- }
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)
- <button type="button" onclick="SendAjaxPOST()">Click Me to Send Ajax(POST) Request</button>
-
- <script>
- function SendAjaxPOST() {
- var xmlHttp;
-
- xmlHttp = null;
-
- if (window.XMLHttpRequest) {
-
- xmlHttp = new XMLHttpRequest();
- }
- else if (window.ActiveXObject) {
-
-
- var strName = "Msxml2.XMLHTTP"
- if (navigator.appVersion.indexOf("MSIE 5.5") >= 0) {
- strName = "Microsoft.XMLHTTP"
- }
- try {
- xmlHttp = new ActiveXObject(strName);
- }
- catch (e) {
- alert("Error. Scripting for ActiveX might be disabled")
- return false;
- }
- }
-
- if (xmlHttp != null) {
-
-
- var userName = "manasm";
-
- xmlHttp.onreadystatechange = function () {
- alert(xmlHttp.readyState);
- if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
- alert(xmlHttp.responseText);
- }
- }
-
-
- xmlHttp.open("POST", "Home/MyAjaxPOST", true);
-
- xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
- xmlHttp.send("userName=manasm&lname=mohaptra");
- }
- }
- </script>
Controller
- [HttpPost]
- public ActionResult MyAjaxPOST()
- {
- ViewBag.Message = "Your app description page.";
- string temp = Request.Form["userName"];
-
- return Json(temp);
- }
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).