AJAX and Classic ASP

Using the xmlhttpserver object in javascript to request an asp page containing script to output text.

UPDATE!! A new version of this article, using jQuery is available here.

Generic cross-browser js function to create an xmlhttpserver object. For a clear introduction to the basics of AJAX, this series of articles is particularly helpful: http://www.ibm.com/developerworks/web/library/wa-ajaxintro1.html.

function GetXmlHttpObject(handler)
{ 
var objXmlHttp=null;

if (navigator.userAgent.indexOf("MSIE")>=0)
{ 
var strName="Msxml2.XMLHTTP";
if (navigator.appVersion.indexOf("MSIE 5.5")>=0)
{
strName="Microsoft.XMLHTTP";
} 
try
{ 
objXmlHttp=new ActiveXObject(strName);
objXmlHttp.onreadystatechange=handler;
return objXmlHttp;
} 
catch(e)
{ 
alert("Error. Scripting for ActiveX might be disabled");
return;
} 
} 
if (navigator.userAgent.indexOf("Mozilla")>=0)
{
objXmlHttp=new XMLHttpRequest();
objXmlHttp.onload=handler;
objXmlHttp.onerror=handler;
return objXmlHttp;
}
} 

Example js function that is fired by a selected index change on an html SELECT element. This one recieves the CustomerID to append to the querystring of the asp script that will get executed. The first js function will call the second StateChanged function, which will output any returned string (responseText) to the innerHTML of a div.

function GetCustomer(id)
{ 
var url="FetchCustomer.asp?CustomerID="  + id ;

xmlHttp=GetXmlHttpObject(stateChanged);
xmlHttp.open("GET", url , true);
xmlHttp.send(null);
} 

function stateChanged() 
{ 
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById('CustomerDetails').innerHTML=xmlHttp.responseText;
}
} 

The select list with the onChange event wired up to the GetCustomer function.

<%
strProvider = "Provider=Microsoft.Jet.OLEDB.4.0;"
strDb = "Data Source=" & Server.MapPath("Northwind.mdb")
strConn = strProvider & strDb
Set Conn = Server.CreateObject("ADODB.Connection")
Conn.Open strConn
Set rs = Conn.Execute("SELECT [CustomerID], [CompanyName] FROM [Customers]")
If Not rs.EOF Then
%>
  <form>
  <select name="CustomerID" onChange="GetCustomer(this.value);">
  <option></option>
<%		
  Do Until rs.EOF
    Response.Write "<option value=""" & rs("CustomerID") & """>" 
    Response.Write rs("CompanyName") & "</option>" & VbCrLf
    rs.MoveNext
  Loop
  rs.Close : Set rs = Nothing : Conn.Close : Set Conn = Nothing 
%>
  </select>
  </form>
<%
Else
  rs.Close : Set rs = Nothing : Conn.Close : Set Conn = Nothing
  Response.Write "<p>Something bad went wrong</p>"
End If
%>
<div id="CustomerDetails"></div>

An example asp script that receives the value from the querystring and queries the database, outputting the result to the http Response, which is received by the xmlhttp object and changes its readystate property and fires the statechanged method, which writes the responseText to the div.

<%@LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<%
strProvider = "Provider=Microsoft.Jet.OLEDB.4.0;"
strDb = "Data Source=" & Server.MapPath("Northwind.mdb")
strConn = strProvider & strDb
Set Conn = Server.CreateObject("ADODB.Connection")
Conn.Open strConn
query = "SELECT * FROM Customers WHERE CustomerID = ?"
CustomerID = Request.QueryString("CustomerID")
arParams = array(CustomerID)
set cmd = Server.CreateObject("ADODB.Command")
cmd.CommandText = query
set cmd.ActiveConnection = Conn
Set rs = cmd.Execute(,arParams,1)
If Not rs.EOF Then
Response.Write rs(1) & "<br />" & _
  rs(4) &  "<br />" & _
  rs(5) & "<br />" & _
  rs(6) & "<br />" & _
  rs(7) & "<br />" & _
  rs(8) & "<br />" & _
  "Tel: " & rs(9) & "<br />"
End If
rs.Close : Set rs = Nothing
set cmd = Nothing 
Conn.Close : Set Conn=nothing
%>

The sample above includes the use of a parameter array passed to the command's execute method. This helps protect against SQL injection.

Date Posted: Sunday, May 6, 2007 11:29 PM
Last Updated: Saturday, January 17, 2009 11:17 PM
Posted by: Mikesdotnetting
Total Views to date: 73110

7 Comments

Thursday, April 9, 2009 10:32 PM - Francisco

Gostaria de um Exemplo completo, não sei onde colocar essas rotinas. Sounovato.

Friday, April 10, 2009 7:59 AM - Mike

@Francisco

The first 3 code blocks go into the page that the user sees. The final block is a complete page.

Tuesday, May 26, 2009 4:30 AM - mehraveh

thank you. Its very good.

Friday, October 16, 2009 5:11 PM - Mike

This is one of the most popular articles on your site. Goes to show Microsoft that classic ASP is alive and well and, well, I for one love it still! Thanks!

Tuesday, December 8, 2009 6:02 AM - John

thanks,

Thursday, January 24, 2013 12:47 PM - usman

how to call a function after statechanged returns a value...
I actually have called ajax on mouse over ... and have to show the result in a small div.. which appears on mouse over ... the issue I am getting is the div appears before the ajax gets the responce and shows nothing if i put delay it gives the same problem. so how can i call a funciton inside state changed.... ????

Saturday, July 13, 2013 10:48 PM - Paul Scannell

I'm implementing this because I have users that use other browsers besides IE. I'm only in the beginning testing phase, but I noticed that I can only run the code snippets once. I have to close the browser and reload it again in order to something a little different. I can't just do a refresh.

Is there a way to create the ajax connection once and then use it over and over with different quereis, etc.?
Add your comment

If you have any comments to make about this article, please use this form to do so. Make sure that your comment relates specifically to the article above. More general comments can be posted through the form on the Contact page.

Please note, all comments are moderated, and some may not be published. The kind of things that will ensure your comment is deleted without ever seeing the light of day are as follows:

  • Not relevant to the article
  • Gratuitous links to your own site or product
  • Anything abusive or libellous
  • Spam
  • Anything in a language I don't understand including gibberish.

I do not pass email addresses on to spammers, so a valid one will assist me in responding to you personally if required.

Recent Comments

Allen Michaels 12/17/2014 4:37 PM
In response to Cascading DropDownLists with jQuery and ASP.NET
Fantastic thank you so much!...

Emily 12/17/2014 12:36 PM
In response to Parameterized IN clauses with ADO.NET and LINQ
Thanks, very helpful!!!! Can i use this for multiple in's ????? IN (.....) and IN(...) and IN...

sss 12/16/2014 3:06 PM
In response to Solving the Operation Must Use An Updateable Query error
good...

Gjuro 12/15/2014 10:30 PM
In response to Examining the Edit Methods and Edit View
You have one fromr (and it should be from, I suppose). :-)...

Gjuro 12/15/2014 10:27 PM
In response to Adding Search
Hi, thnx for all this C#->VB translations. Yet, the following code block is (slightly) in error it a...

Scot 12/14/2014 1:39 PM
In response to Entity Framework 6 Recipe - Alphabetical Paging In ASP.NET MVC
Thanks,Mike I found solution....

Gjuro 12/13/2014 10:52 PM
In response to Accessing Your Model's Data from a Controller
The article mentions "Creating an Entity Framework Data Model for an ASP.NET MVC Application" (at is...

Samuel 12/13/2014 8:40 AM
In response to Displaying The First n Characters Of Text
I have failed to use the extension because it throws an error that it doesn't recognise the chop be...

Ignas 12/12/2014 5:11 PM
In response to Cleaner Conditional HTML Attributes In Razor Web Pages
Any suggestions for Html Helper elements with HtmlAttributes, when you need to conditionally set it...

Gautam 12/11/2014 8:50 PM
In response to Validation In Razor Web Pages 2
Hi Mike Is this required for V3, non html helper input...