AJAX Application in ASP.NET


Here we create a simple application using AJAX in ASP.NET. When we create an Ajax enabled webpage, we use an XMLHttpRequest object, which is used to provide communication with the server without posting the page back to the server. We have to initiate this object differently for different browsers.

var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")

By this, we create an instance of the XMLHttpRequest object.

In Mozilla and FireFox, we use the following code to create the instance of the XMLHttpRequest object.

var xmlHttp = new XmlHttpRequest();

Now we take an example of a simple ajax application in which we read the Text File ( My.txt ) and show the Text of the Text File in the alert box.

Step 1: First we write the following js code in the .aspx page:

<script language="JavaScript" type="text/javascript" >
var xmlHttp
var arr;
function ShowText()
{
      xmlHttp=GetXmlHttpObject()
      xmlHttp.onreadystatechange=stateChanged
      xmlHttp.open("GET","My.txt",true)
      xmlHttp.send(null)
      return false;
}
function stateChanged()

{

      if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")

      {

      alert(xmlHttp.responseText);
      }
}    
function GetXmlHttpObject()

{

      var objXMLHttp=null
      if (window.XMLHttpRequest)
      {
      objXMLHttp=new XMLHttpRequest()
      }
      else if (window.ActiveXObject)
      {
      objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
      }
      return objXMLHttp
}

 </script>

NOTE:

function ShowText()
{
      xmlHttp=GetXmlHttpObject()
      xmlHttp.onreadystatechange=stateChanged
      xmlHttp.open("GET","My.txt",true)
      xmlHttp.send(null)
      return false;
}


Here we use the XMLHttpRequest object's GET/Open method to read a text file ( My.txt) on the server and display its text in the Alert Box.

Step 2: Add the Text File (My.txt) in the project and write the following code in the body part:

<body onload="ShowText()">
    <form id="form1" runat="server">
    <div>

    </div>
    </form>
</body>

Here we call the ShowText() function. When we run the program the Text of the Text File appears in the Alert Box.

Ajax.gif

Up Next
    Ebook Download
    View all
    Learn
    View all