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.