XMLHttpRequest functions

See section 10A of the book.

This is the XMLHttpRequest function I always use; see quirksmode.js, the script file that's used in every page on this site. It is presented very shortly; section 10A of the book treats these functions in detail.

function sendRequest(url,callback,postData) {
	var req = createXMLHTTPObject();
	if (!req) return;
	var method = (postData) ? "POST" : "GET";
	req.open(method,url,true);
	req.setRequestHeader('User-Agent','XMLHTTP/1.0');
	if (postData)
		req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
	req.onreadystatechange = function () {
		if (req.readyState != 4) return;
		if (req.status != 200 && req.status != 304) {
//			alert('HTTP error ' + req.status);
			return;
		}
		callback(req);
	}
	if (req.readyState == 4) return;
	req.send(postData);
}

var XMLHttpFactories = [
	function () {return new XMLHttpRequest()},
	function () {return new ActiveXObject("Msxml2.XMLHTTP")},
	function () {return new ActiveXObject("Msxml3.XMLHTTP")},
	function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];

function createXMLHTTPObject() {
	var xmlhttp = false;
	for (var i=0;i<XMLHttpFactories.length;i++) {
		try {
			xmlhttp = XMLHttpFactories[i]();
		}
		catch (e) {
			continue;
		}
		break;
	}
	return xmlhttp;
}

It's used like this:

sendRequest('file.txt',handleRequest);

Now the file file.txt is fetched, and when that's done the function handleRequest() is called. This function receives the XMLHttpRequest object as an argument, which I traditionally call req (though, of course, you can use any variable name you like). Typically, this function reads out the responseXML or responseText and does something with it.

function handleRequest(req) {
	var writeroot = [some element];
	writeroot.innerHTML = req.responseText;
}

One object per request

This function creates a new XMLHttpRequest object for every request you make. In simple cases such as this site, where every page fetches only three to five files, I don't mind creating three to five objects. In more complex sites, however, where any page can make an arbitrary amount of requests, it's probably better to write a function that reuses existing XMLHttpRequest objects.