Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Raw AJAX

3.67/5 (2 votes)
27 May 2012CPOL3 min read 19.2K  
Use of XMLHTTPREQUEST (Raw AJAX).

Introduction

In this article I demonstrate the use of XMLHTTPREQUEST. This is a small sample project showing the use of "Raw Ajax".

"Raw Ajax", in simple words, is the use XMLHTTPREQUEST to communicate to the database server. Using the XMLHTTPREQUEST object, we can communicate to the database server without posting the full page, this really improves the performance of the application. Now the question is!, what exactly is XMLHTTPREQUEST?

XMLHTTPREQUEST in simple terms is an object of the browser (IE, Mozilla, Opera etc.). We can make use of the XMLHTTPREQUEST object using scripting language like JavaScript.  

Background

The important thing to know is that, to communicate to the database server you have to write code. Just write the code in a different page, and create a separate page to make a call to that page (that contains the code). One more thing in the UI part: erase all markup tags, but leave the top most line in the page; in the case of .NET, it is:

ASP.NET
"<%@ Page Language="C#" AutoEventWireup="true" 
               CodeFile="index.aspx.cs" Inherits="_Default" %>"

Is you don't erase the markup tags, then this will be added to the response in return.

First try the example without erasing and see what you see for better understanding, after that erase that in real scenario. 

Now, let's see how it works. 

Using the code

Here I have created two different blocks:

Block 1: Contains the programming logic to communicate to the database server to fetch the data (my code only contains the code to fetch the data but you can write the code for tasks like update, delete, insert, etc.). 

Block 2: Contains the script block to make a call to that page containing the programming code.

Now, here we have to make a call to different page and along with this we have to carry some of our values to that page like the unique value according to which we will be fetching the values or the values to be modify etc. So to carry those values i have set the query strings.

Working: There are four steps:

1. Initialize the XMLHTTPREQUEST object according to the browser.

2. Make a call to the page containing the code to communicate to the database server using the open method of the XMLHTTPREQUEST object. The open method basically requires three argument: the request method (GET, POST, etc.), the URL to the page containing the code to communicate to the database server, and a boolean indicator for either synchronous or asynchronous processing.

3. To set, assign the function (specify what to do with the response from the database server) to the onreadystatechange property of the XMLHTTPREQUEST object.

4. We can send a request to the server using the send method of the XMLHTTPREQUEST object. 

ASP.NET
<%@ Page Language="C#" AutoEventWireup="true" 
             CodeFile="index.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
           "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    <!--Block 1 -->
    <script type="text/javascript" language="javascript">
        function getValues()
        {
            var XHTTP;
            try
            {
                //For morden versions Internet Explorer
                XHTTP = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (ex)
            {
                try
                {
                    try
                    {
                        //For old versions Internet Explorer
                        XHTTP=new ActiveXObject("Microsoft.XMLHTTP");
                    }
                    catch(exxx)
                    {
                        XHTTP = new XMLHttpRequest("Msxml2.XMLHTTP");
                    }
                }
                catch(exx)
                {
                    try
                    {
                        //For browsers other than Internet Explorer
                        XHTTP= new XMLHttpRequest();
                    }
                    catch(eexx)
                    {
                        //This means ActiveX is not enabled.
                        //To enabled go to your browser settings and enabled the ActiveX.
                        alert("Not Supported, It might be previous version browser");                        
                    }
                }
            }
            //To fetch the data on the basis of particular id.
            var id=document.getElementById("<%=txtId.ClientID %>").value;
            
            //This opens the page where the Data Access Layer logic is written.
            //In this demo it is XMLHTTPPage.aspx.
            XHTTP.open("GET","XMLHTTPPage.aspx?id="+id,true);
            
            //This is to set the function on the onreadystatechange event
            //onreadystatechange is the event which fires when XMLHTTPREQUEST's state changes.
            //Different States Given Below---
            //1. UNSENT
            //2. OPENED
            //3. LOADING
            //4. DONE
            XHTTP.onreadystatechange= function()
            {
                if (XHTTP.readyState==4)
                {
                    var result=XHTTP.responseText.toString().split("~");
                    if(result.length>1)
                        alert("Name = "+result[0].toString().trim()+", 
                          Hobby = "+result[1].toString().trim()+", 
                          Age = "+result[2].toString().trim());
                    else
                        alert(XHTTP.responseText.toString().trim());
                }
            }
            //This finlly send the request.
            XHTTP.send(null);
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <span>ID </span><asp:TextBox ID="txtId" runat="server"></asp:TextBox><br />
        
        <input type="button" id="btnGet" value="Get Values" onclick="getValues();" />
    </div>
    </form>
</body>
</html>
C#
 /*
   Block 2
   This code is written in the different page.
   (Name :- "XMLHTTPPage.aspx" as you can see 
   this page we have use in our block 1 script)
   to make a call to that page.
*/
public partial class XMLHTTPPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("SERVER=.;UID=sa;PWD=gaurav;DATABASE=TEST");


        if (Request.QueryString["id"] != "")
        {
            SqlDataAdapter adap = new SqlDataAdapter("SELECT * FROM Test_Table WHERE pid='" + 
                                  Request.QueryString["id"] + "'", con);
            DataSet ds = new DataSet();
            adap.Fill(ds);
            if (ds.Tables[0].Rows.Count > 0)
            {
                string result = ds.Tables[0].Rows[0]["pname"].ToString() + "~" + 
                  ds.Tables[0].Rows[0]["hobby"].ToString() + "~" + 
                  ds.Tables[0].Rows[0]["age"].ToString();
                Response.Write(result);
            }
            else
            {
                Response.Write("No Data Found");
            }
        }
        else
        {
            Response.Write("No Data Found");
        }

        //Response.Write :- writes the response from the database server
        //to the response buffer of page that will be then can be get 
        //by the responseText or responseXML property of XMLHTTPREQUEST.
    }
} 

Points of Interest

In the initializing part of XMLHTTPREQUEST, I have created a try-catch hierarchy to allocate the memory to XMLHTTPREQUEST according to the browser. Because we don't know which browser the user is using. To allocate the XMLHTTPREQUEST memory, a try-catch approach is used. For your better understanding I have added comments. 

Finally

Well, this is a very basic sample project of using XMLHTTPREQUEST. There is lot more to learn in using XMLHTTPREQUEST. So good luck in your future learning.  

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)