By now, everyone and their dogs have jumped on to the AJAX bandwagon in order to make their web applications faster and enhance the user experience. (What? Your dog doesn't code? Hmmmm.) Like most programmers, I am lazy and didn't like writing my AJAX code over and over, so I went in search of a solid AJAX library. While there are lots of AJAX libraries out there with tons of bells and whistles, I wanted something simple and yet flexible. I also saw a lot of implementations of AutoComplete boxes and various other common AJAX scenarios, but I wanted an AJAX library that I could re-use, no matter what the project called for.
- Simple to use.
- Must be flexible enough to handle any AJAX scenario.
- Must be able to pass parameters to the
XmlHttpRequest's callback function
- Must be completely self-contained with no global variables, to ensure compatibility with unknown scripts.
setDefinitionfunctions, and wired up the the
getDefinitionfunction to the
onchangeevent of a
function getDefinition(term, textareaID, borderStyle,
if(term != "")
var url = "lookupDefinition.aspx?term=" + term
var ajax = new AjaxDelegate(url, setDefinition,
textareaID, borderStyle, borderWidth, borderColor);
function setDefinition(url, response, textareaID,
borderStyle, borderWidth, borderColor)
var word = eval(response);
var textarea = document.getElementById(textareaID);
textarea.value = word.definition;
textarea.style.borderStyle = borderStyle;
textarea.style.borderWidth = borderWidth + 'px';
textarea.style.borderColor = borderColor;
Under the HoodWhen the
onchangeevent fires, the
getDefinitionfunction is called. Within that function, a new
AjaxDelegateobject is created. The first parameter is the URL of the page that will do the behind-the-scenes processing. The second parameter is the name of the callback function that will get executed when the asynchronous call completes. After that, you can pass any number of additional arguments to the
AjaxDelegateconstructor. The neat part here is that all of these additional arguments will be available to the callback function when the call completes. Finally, make sure to call the
Fetch()method to kick off the processing.
This example is making a simple
GETrequest, but if you set the contents of the
.formDataproperty, the underlying function will make a
POSTrequest and pass the data to the url specified. This example also uses the
responseXMLby setting the
.isXMLproperty before calling the
eval()function to parse it). I will admit the the example is overly-simplistic and not very useful, but the point is to demonstrate the concept.
XmlHttpRequestobject with global scope that may conflict with the usage of other libraries or unknown scripts.
Download the AjaxDelegate library