Understanding and Using AJAX

Suppose this is our simple ASP.NET page i.e. MyPage.aspx which would be called using AJAX

Code for MyPage.aspx.cs

protected void Page_Load(object sender, EventArgs e)

{

// no data is passed

if (Request.QueryString[“myGetData”] == null)

{

Response.Write(“Hello World”);

}

// if GET method is used to call this page

else if (Request.QueryString[“myGetData”] != null)

{

Response.Write(“Hello “ + Request.QueryString[“name”].ToString());

}

// if POST method is used to call this page

else if (Request.Form[“myPostData”] != null)

{

Response.Write(“My Post Data is “ + Request.Form[“myPostData”].ToString());

}

}

Delete everything from MyPage.aspx page just keep the page directive otherwise html tags would also be sent as a part of response.

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Mypage.aspx.cs” Inherits=”MyPage” %>

Now the javascript code to call the page asynchronously using AJAX. Comment/Uncomment the particular section of code to test the functionality

<script type=”text/javascript”>

var request=null;

function CreateRequest()

{

try

{

// create a new object to talk HTTP with a web server.

// XMLHttpRequest – works on Safari,Firefox, Mozilla, Opera , IE 7 and most other browsers

request=new XMLHttpRequest();

}

catch(trymicrosoft)

{

try

{

// Msxml2.XMLHTTP – Most version of IE support this

request=new ActiveXObject(“Msxml2.XMLHTTP”);

}

catch(othermicrosoft)

{

try

{

//Microsoft.XMLHTTP – but for some, we’ll need this other type

request=new ActiveXObject(“Microsoft.XMLHTTP”);

}

catch(failed)

{

request=null;

}

}

}

if(request==null)

alert(‘Error creating request object’);

else

{

// i.e. space with %20

// if no data is to be send

var url=“MyPage.aspx”;

// open-initialize the connection

// GET – specify how to send data to the server

// url- url to send the request

// asynchrounous – true

request.open(“GET”,url,true);

// telling the browser what to do with the server’s response

// i.e. the function to be called when response is received

// onreadystatechange- this property affects every ready state not just the one indicating

// that the server is finished with request

request.onreadystatechange=updatepage;

// send the request

// no data is required so send null

// for using send() to pass data to a server requires POST method for the request and need to specify content type

request.send(null);

// if data is to be send using GET i.e. as query string

var name=“MyName”;

// escape() function replaces characters like space with something that will work as a part of a request URL.

var url=“MyPage.aspx?myGetData=”+escape(name);

request.open(“GET”,url,true);

request.onreadystatechange=updatepage;

request.send(null);

// if more data is to be send than use post

var name=“MyName”;

var url=“MyPage.aspx”;

request.open(“POST”,url,true);

request.onreadystatechange=updatepage;

//setRequestHeader()- allows us to add information to the request usual intended for use by the server

// Content-Type – is the name of the request header

// application/x-www-form-urlencoded – the value of the request header

// this tells the server that the data is encoded like it would be in a request URL

// for passing XML content replace “application/x-www-form-urlencoded” with “text\xml”

request.setRequestHeader(“Content-Type”,“application/x-www-form-urlencoded”);

// specify the data to be send

// escape() function replaces characters like space with something that will work as a part of a request URL.

request.send(“myPostData=”+escape(name));

}

}

// updatepage – this function will get run every time the ready state changes

function updatepage()

{

// readyState=this property of the request object stores the current state

// if 4 means server is done with the request

// if 0 i.e uninitialized

// if 1 i.e open, the object has been created but the send method has not been called

// if 2 i.e. sent, the send method has been called.

// if 3 i.e. receiving , responseText is not available but some data has been received

// if 4 i.e. loaded, all the data has been received, responseText is available

if(request.readyState==4)

{

// check for the status send by the server

// if 200 i.e. everything is fine

// if 404 i.e. if the page specified in the url is not found

if(request.status==200)

{

var myResponse=request.responseText;

alert(myResponse);

}

else

{

alert(“Error! Request status is “ +request.status);

}

}

}

</script>

<input id=”Button1″ type=”button” value=”button” onclick=”CreateRequest()”/>

Bye…


Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

2 thoughts on “Understanding and Using AJAX”

  1. I’m so glad to have found your web page. My pal mentioned it to me before, yet never got around to checking it out until now. I must express, I’m floored. I really enjoyed reading through your posts and will absolutely be back to get more.

    Like

Share your thoughts

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s