AJAX Basic Part -II

Hello friends ,

Here  i am with next topic of AJAX  basic which is part II. so next step is simple example so  here we go with simple example.

As part of AJAX basic I just come with below example in this we create two page one is with server coding & another with client coding.

My main aim here to get result by ajax with out post back so we just try to get current time as result.

For this we write code in default.aspx page as below

<script language =”javascript” type=”text/javascript” >

var myServerRequest;

function callAjax() {

try {

myServerRequest = new XMLHttpRequest();

myServerRequest.status

 

}

catch (ex) {

try {

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

}

catch (ax) {

try {

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

}

catch (ax1) {

return false;

}

}

}

}

function Callserver() {

callAjax();

if (myServerRequest != null) {

myServerRequest.open(‘GET’, “serverCode.aspx”, true);

myServerRequest.onreadystatechange = myServerResponse;

myServerRequest.send();

}

return false;

}

function myServerResponse() {

if (myServerRequest.readyState == 4) {

if (myServerRequest.status == 200) {

document.getElementById(‘dvResult’).innerHTML = myServerRequest.responseText;

} else {

document.getElementById(‘dvResult’).innerHTML = ‘Oops Error’;

}

}

return false;

 

}

</script>

Here we have 3 main function

1. CallAjax :- it is responsible for Assigning XMLHttpRequest Object.

2. myserverResponse :- by the name it is clear that it use for holding the result what ever pass by server.

3. callServer :- This function is call on any event on button and it sum up the above 2 events.

On server Page at page load we do following code

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

Response.Write(Now.ToString)

Response.End()

End Sub

Here we just write time as response then we end response.

If you do not do response.end() then html of server page also comes.

you can download the code from

simpleajax

just copy and paste code in your page and it will work.

Thanks

Rajat

Advertisements

Leave a Reply

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