< Back to Code Samples
/*
* This micro-library is a couple very rudimentary AJAX functions that we occasionally use
* when we just need some super-simple asynchronous calls. For more involved stuff, we use
* prototype.
*
*/
/**
* Short and sweet -- gets an XMLHttpRequest object for Asynch calls.
* @return the XHR object
*/
function GetXHR()
{
var XHR=null;
try
{
// Firefox, Opera 8.0+, Safari
XHR=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
XHR=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
XHR=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return XHR;
}
/**
* This is a basic makerequest function. I think I derived this from something
* in a Lee Babin book (that one on the Apress label about AJAX & PHP?). I've
* hacked it up quite a bit though to incorporate some additional functionality.
*
* 1. This supports form POSTing directly now.
* 2. The response is flexibly guided into any number of possible outcomes.
* a) Using an object as the argument will stick the response text in
* either the innerHTML or SRC attribute. [for regular DOM nodes or
* IMG objects]
*
* b) Using a function allows for this result to be chained into other
* AJAX calls, ensuring that there are no racing conditions created
* by laggy requests.
*
* c) Using a variable will simply set the variable to the result. This
* can be a little risky if the connection is laggy. We tend to
* avoid this option.
*/
function makerequest(serverPage, obj, getOrPost, str)
{
//
// These three lines allow legacy functionality with older
// versions of the functions, which didn't use the 3rd and
// 4th parameters. Old uses still need to now pass the
// actual object instead of just the ID of the object.
//
var undefined;
if (str == undefined) { str = null; }
if (getOrPost == undefined || getOrPost.toUpperCase() != "POST")
{ getOrPost = "GET"; }
var XHR;
if(XHR = GetXHR()) {
XHR.open (getOrPost, serverPage, true);
if (getOrPost.toUpperCase() == "POST")
{
XHR.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
XHR.setRequestHeader("Content-Length", str.length);
XHR.setRequestHeader("Connection", "close");
}
XHR.onreadystatechange = function() {
if (XHR.readyState == 4 && XHR.status == 200 && obj != null)
{
switch(typeof(obj)) {
// Allows for AJAX chaining //
case "function":
obj(XHR.responseText);
break;
case "object":
if (obj.innerHTML)
{
obj.innerHTML = XHR.responseText;
}
else obj.src = XHR.responseText;
break;
default:
obj = XHR.responseText;
break;
}
}
}
XHR.send(str);
}
}