Click here to Skip to main content
15,884,075 members
Articles / Programming Languages / Javascript
Article

Using AJAX to fetch data from ASP script

Rate me:
Please Sign up or sign in to vote.
2.73/5 (14 votes)
10 Oct 20053 min read 76.4K   629   12   7
Using AJAX to fetch data from a server (ASP script) without refreshing.

Introduction

What is ajax:

AJAX or Asynchronous JavaScript and XML is a term describing a web development technique for creating interactive web applications using a combination of: * HTML (or XHTML) and Cascading Style Sheets for presenting information* Document Object Model, JavaScript to dynamically display and interact with the information presented* XML, XSLT and the XMLHttpRequest object to interchange and manipulate data asynchronously with the web server (although AJAX applications can use other technologies

want more details click here
ere we have seen 2 files.
file1-->asp_server.asp
file2-->reply_test.htm

reply_test.htm in this file have three functions in javascripts...
it will work both ie and opera and firefox.

creat_Object()

sever_interaction()

call_server()

user clik that button its call the javascript function
First we initialise the xmlhttprequest object..

function creat_Object();
{
var xmlhttp;
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') 
{
try 
{
xmlhttp = new XMLHttpRequest();
} 
catch (e) 
{
alert("Your browser is not supporting XMLHTTPRequest");
xmlhttp = false;
}
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp; 
} 
var request = creat_Object(); 

Once an XMLHttpRequest object has been created, we must call two separate methods in order to get it to retrieve data from a server.

open() initialises the connection we wish to make, and takes two arguments, with several optionals. The first argument is the type of request we want to send; the second argument identifies the location from which we wish to request data. For instance, if we wanted to use a GET request to access asp_server.asp at the root of our server, we'd initialise the XMLHttpRequest object like this:

request.open("GET", "asp_server.asp"); 

The URL can be either relative or absolute, but due to cross-domain security concerns, the target must reside on the same domain as the page that requests it.

The open() method also takes an optional third boolean argument that specifies whether the request is made asynchronously (true, the default) or synchronously (false). With a synchronous request, the browser will freeze, disallowing any user interaction, until the object has completed. An asynchronous request occurs in the background, allowing other scripts to run and letting the user continue to access their browser. It's recommended that you use asynchronous requests; otherwise, we run the risk of a user's browser locking up while they wait for a request that went awry. open()'s optional fourth and fifth arguments are a username and password for authentication when accessing a password-protected URL.

Once open() has been used to initialise a connection, the send() method activates the connection and makes the request. send() takes one argument, allowing us to send extra data, such as asp querystring variables, along with the call.

request.send(null); 

Here just we get the data from asp_server.asp file so we dont want use query string variables...

request.open("GET", "asp_server.asp"); 
request.onreadystatechange = sever_interaction;
request.send(null); 
once we've called send(), XMLHttpRequest will contact the server and retrieve the data we requested; however, this process takes an indeterminate amount of time. In order to find out when the object has finished retrieving data, we must use an event listener. In the case of an XMLHttpRequest object, we need to listen for changes in its readyState variable. This variable specifies the status of the object's connection, and can be any of the following:
0 – Uninitialised 
1 – Loading 
2 – Loaded 
3 – Interactive 
4 – Completed 
Changes in the readyState variable can be monitored using a special onreadystatechange listener, so we'll need to set up a function to handle the event when the readyState is changed here we use that function name is sever_interaction()

readyState increments from 0 to 4, and the onreadystatechange event is triggered for each increment, but we really only want to know when the connection has completed (4), so our handling function needs to realise this. Upon the connection's completion, we also have to check whether the XMLHttpRequest object successfully retrieved the data, or was given an error code, such as 404: "Page not found". This can be determined from the object's status property, which contains an integer code. "200" denotes a successful completion, but this value can be any of the HTTP codes that servers may return.

function sever_interaction()
{
if(request.readyState == 1)
{
document.getElementById('aja_cnts').innerHTML='';
document.getElementById('aja_cnts').innerHTML = 'Loading...';
}
if(request.readyState == 4)
{
if (request.status == 200) 
{ 
var answer = request.responseText;
document.getElementById('aja_cnts').innerHTML='';
document.getElementById('aja_cnts').innerHTML = answer;
}
}
} 

Even though the XMLHttpRequest object allows us to call the open() method multiple times, each object can really only be used for one call, as the onreadystatechange event doesn't update again once readyState changes to "4" (in Mozilla). Therefore, we have to create a new XMLHttpRequest object every time we want to make a remote call.

asp_server.asp
-------------------- 

dim v_nme,v_city
v_nme="name : New Begin"
v_city="City : Chennai"
Response.Write(v_nme&"Sample from Server "&v_city) 
reply_test.htm
---------------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "<A href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd</A>">
<html xmlns="<A href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</A>">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Getting Server side data using AJAX</title>
</head>
<script>
function creat_Object()
{ 
var xmlhttp;
// This if condition for Firefox and Opera Browsers 
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') 
{
try 
{
xmlhttp = new XMLHttpRequest();
} 
catch (e) 
{
alert("Your browser is not supporting XMLHTTPRequest");
xmlhttp = false;
}
}
// else condition for ie
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}

var request = creat_Object();
function sever_interaction()
{
if(request.readyState == 1)
{
document.getElementById('aja_cnts').innerHTML='';
document.getElementById('aja_cnts').innerHTML = 'Loading...';
}
if(request.readyState == 4)
{
var answer = request.responseText;
document.getElementById('aja_cnts').innerHTML='';
document.getElementById('aja_cnts').innerHTML = answer;
}
}
function call_server()
{
request.open("GET", "asp_server.asp"); 
request.onreadystatechange = sever_interaction;
request.send('');

}
</script>
<body>
<table width="80%" border="1" cellspacing="2">
<caption>
Using AJAX
</caption>
<tr>
<td width="16%" height="90"> </td>
<td width="23%"><label>
<input type="button" name="Button" value="Button" onclick="call_server();" />
</label></td>
<td width="61%"><div id="aja_cnts"> </div></td>
</tr>
</table>
</body>
</html> 


License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior)
United States United States
Rich development experience in Internet/Intranet based applications using Dot net C# , ASPX , ASP, MS SQL Server,AJAX, JavaScript,HTML,XML,CSS.

Comments and Discussions

 
Generalloading animation Pin
Tim Austin10-Jul-08 1:58
Tim Austin10-Jul-08 1:58 
Generalflashing effect Pin
webber12345621-Sep-06 6:21
webber12345621-Sep-06 6:21 
GeneralRe: flashing effect Pin
newbegin28-Sep-06 5:21
professionalnewbegin28-Sep-06 5:21 
GeneralRe: flashing effect Pin
webber12345628-Sep-06 9:10
webber12345628-Sep-06 9:10 
Generaljavascript for printing word document Pin
Deepak_DOTNET21-Feb-06 18:29
Deepak_DOTNET21-Feb-06 18:29 
QuestionWhere .NET comes into scene? Pin
vadivelkumar10-Oct-05 20:56
vadivelkumar10-Oct-05 20:56 
AnswerRe: Where .NET comes into scene? Pin
webber12345621-Sep-06 6:20
webber12345621-Sep-06 6:20 
Just point it to a .aspx file instead of a .asp file

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.