A Simple Classic ASP and AJAX Example

So you're still using Classic ASP, but need to implement some AJAX effects. To get started, its so much easier than you think (view the demo). You'll need a basic knowledge of Javascript and Classic ASP to build your first AJAX enabled page.

There are 3 parts to every AJAX request.

  1. The Request Page - this can be HTML, ASP, ASPX, PHP or any other type of web page you need to work with.
  2. Javascript Functions - these are included in the Request Page, and handle the AJAX request and response.
  3. The Server Side Page - this page recieves the request on the server, and sends something back to the Javascript Function

Our simple example will contain a web page with a button, when clicked the page will go to the server, and come back with a simple message. All of this will occur without the page reloading, giving us the magical AJAX effect!

1. The Request Page

This page can be any type of web page, and can provide many ways of launching an AJAX request. For our simple example, we are going to use a button, and a Div to show the response.

Consider the following piece of code; a HTML button that calls some javascript when clicked, and a DIV

<button onclick="javascript:getMessage();">Get Message From Server</button>
   
<div id="responseDiv">original text</div>

This is all the HTML we need in our test page, next we will look at the Javascript required to get things working.

2. The Javascript Functions

We will be using a very simple, but effective AJAX request library, called XHConn. It simply allows us to make a request to a server side page, with javascript, and handle the result.

The function that does all the work is shown below, be sure to include the license text at the top, its important to give credit for open source projects you use.

To start with, you will need to include the following standard library code in the top of your Request Page:

/** XHConn - Simple XMLHTTP Interface - bfults@gmail.com - 2005-04-08        **
 ** Code licensed under Creative Commons Attribution-ShareAlike License      **
 ** http://creativecommons.org/licenses/by-sa/2.0/                           **/
function XHConn()
{
  var xmlhttp, bComplete = false;
  try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
  catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
  catch (e) { try { xmlhttp = new XMLHttpRequest(); }
  catch (e) { xmlhttp = false; }}}
  if (!xmlhttp) return null;
  this.connect = function(sURL, sMethod, sVars, fnDone)
  {
    if (!xmlhttp) return false;
    bComplete = false;
    sMethod = sMethod.toUpperCase();
    try {
      if (sMethod == "GET")
      {
        xmlhttp.open(sMethod, sURL+"?"+sVars, true);
        sVars = "";
      }
      else
      {
        xmlhttp.open(sMethod, sURL, true);
        xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
        xmlhttp.setRequestHeader("Content-Type",
          "application/x-www-form-urlencoded");
      }
      xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState == 4 && !bComplete)
        {
          bComplete = true;
          fnDone(xmlhttp);
        }};
      xmlhttp.send(sVars);
    }
    catch(z) { return false; }
    return true;
  };
  return this;
}

Now that the XMLHTTP Request library is set to go, we are going to include a generic AJAX function I wrote, which you can reuse for most scenarios.

// doAJAXCall : Generic AJAX Handler, used with XHConn
// Author : Bryce Christensen (www.esonica.com)
// PageURL : the server side page we are calling
// ReqType : either POST or GET, typically POST
// PostStr : parameter passed in a query string format 'param1=foo¶m2=bar'
// FunctionName : the JS function that will handle the response

var doAJAXCall = function (PageURL, ReqType, PostStr, FunctionName) {

	// create the new object for doing the XMLHTTP Request
	var myConn = new XHConn();

	// check if the browser supports it
	if (myConn)	{
	    
	    // XMLHTTPRequest is supported by the browser, continue with the request
	    myConn.connect('' + PageURL + '', '' + ReqType + '', '' + PostStr + '', FunctionName);    
	} 
	else {
	    // Not support by this browser, alert the user
	    alert("XMLHTTP not available. Try a newer/better browser, this application will not work!");   
	}
}

Now we are ready to include our function that gets called when the button is clicked. In this case, we are calling an ASP page on the server called 'serversidetest.asp' and passing the response to a Javascript function called showMessageResponse.

// launched from button click 
var getMessage = function () {
	
	// build up the post string when passing variables to the server side page
	// var PostStr = "variable=value&variable2=value2";
	var PostStr = "";
	
	
	// use the generic function to make the request
	doAJAXCall('serversidetest.asp', 'POST', '' + PostStr + '', showMessageResponse);
}

And the function 'showResponseMessage()' now for handling the response from the server side page (serversidetest.asp)

// The function for handling the response from the server
var showMessageResponse = function (oXML) { 
    
    // get the response text, into a variable
    var response = oXML.responseText;
    
    // update the Div to show the result from the server
	document.getElementById("responseDiv").innerHTML = response;
};

3. The Server Side Page

Your almost there, now for the part you will know well, the ASP page. For this example, we are just going to get our ASP page to respond with the current server time.

<%@ Language=VBScript %>
Response.Write "The Server time is " & Now()

Note that we could use any type of server side page that will give us a response, and example in ASP.Net C# would be

<%@ Page Language="C#" %>
<% Response.Write("The Server Time is " + System.DateTime.Now.ToLongTimeString()); %>

That's all the coding required, you can download the files for the demo below for the quick solution.

Sample Files & Demo

You can download the files for the example in the zip file link below.

Download the Example Code

You can see the demo in action here : Simple AJAX Example

bryce@esonica.com