Simple AJAX Module

21 Jun 2007 by Dan,

Before you can start doing any cool stuff with AJAX you have to have the asynchronous data transfer part figured out.

This is a simple module I’ve used in a number of applications. It’s lightweight, and creates a transfer object without resorting to browser detection which gives it a fair shot at working with future versions of browsers.

It’s also pretty simple to customize, so long as you have a decent understanding of javascript and the concept of callback functions. Enjoy!

function stateChanged(){
if (xmlHttp.readyState==4 || xmlHttp.readyState==”complete”){
xml = xmlHttp.responseXML;
//do something with your returned xml here
}
}
function GetXmlHttpObject(){
var objXmlHttp = null
if (window.XMLHttpRequest){
objXmlHttp = new XMLHttpRequest();
}
else if (typeof ActiveXObject != “undefined”){
objXmlHttp = new ActiveXObject(”Microsoft.XMLHTTP”);
}
return objXmlHttp
}

And here is an example of a function that uses the object and callback function:

function postalSearch(){
var str = document.getElementById(”txtPostal”).value;
if (str.length > 0){
var url=”/include/postal.php?postal=” + str
xmlHttp=GetXmlHttpObject()
if (xmlHttp){
xmlHttp.onreadystatechange = stateChanged
xmlHttp.open(”GET”, url , true)
xmlHttp.send(null)
}
}
}

2 Comments

  1. hi
    dxushah0zlgtdiy8
    good luck

  2. hi
    dxushah0zlgtdiy8
    good luck

Leave a Reply

More from Dan

Follow Me! Follow Me! Follow Me! Follow Me!
 
 
The Website Grade for www.abdinoor.com!