02/20/06: Multiple XMLHttpRequest 2
Category: AJAX
File : xhrmulti.php
Includes : Multi-XHR request Javascript, XHR Javascript
As it turns out, simply declaring the variable local to the creatXMLHttp request function and passing it to the calling function directly was all that I needed. I revised the xhrmulti.php to reflect that. I do the onstatechange handling in the calling function, but that's just an extra if statement.
Here's the code for the new xhrRequest() function and a calling function, doSomething():
// Luis Torrefranca 02/2006
function xhrRequest(type) {
var xhrSend;
if (!type) {
type = 'text';
}
if (window.ActiveXObject) {
try {
xhrSend = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhrSend = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
} else if (window.XMLHttpRequest) {
xhrSend = new XMLHttpRequest();
if (xhrSend.overrideMimeType) {
xhrSend.overrideMimeType('text/' + type);
}
}
return (xhrSend);
}
function doSomething(url, reqType) {
if (!reqType) {
reqType = "html";
}
var xhrRec = xhrRequest(reqType);
xhrRec.open('GET', url, true);
xhrRec.send(null);
xhrRec.onreadystatechange = function() {
if (xhrRec.readyState == 4 && xhrRec.status == 200) {
///////////////////////////////////
// Do something with the received data
///////////////////////////////////
}
};
}
And somewhere in the HTML...
<div onclick="doSomething('url of the file you're requesting via XHR', 'xml or html, depending on what you're retrieving');">Click me to do something</div>