Full title — Javascript: prototyped Ajax handlers allow for multiple Ajax requests at the same time, returning to the same function (if needed). The Javascript here is adapted from source in O’Reilly’s AJAX Hacks [ go ], by Bruce Perry.
The setup in the book looks like this:
Function A: combined data into a GET or POST string
Function B+C: accepts GET or POST string, sends http request, then calls function C with the result
Function D: accepts the return (XML, plain text), and DOM’s, etc., the data to where it is needed.
Problem is, the way this book had things programmed,
1) Only one http request could be sent at the same time
2) If 1) is solved, then only one request could be sent to the same callback function (C) at the same time.
I solved this using a small amount of prototyping, and localizing the ajax handler’s function variables. See below:
Function A (create the GET string):
function ajaxSaveTag(tag) {
var url = 'ajax/ajaxSaveTags.php';
url += '?tags='+encodeURIComponent(tag);
httpRequest("GET",url,1,new ReturnSaveTag());
}
Function B+C (ajax handlers):
function httpRequest(type,url,asynch,respHandle) {
var request;
// moz
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
// ie
else if (window.ActiveXObject) {
request = new ActiveXObject("Msxml2.XMLHTTP");
if (!request) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
}
// send request | error
if (request) {
if (type.toLowerCase() != "post") {
initRequest(request,type,url,asynch,respHandle);
} else {
var args = arguments[4];
if (args != null && args.length > 0) {
initRequest(request,type,url,asynch,respHandle,args);
}
}
} else {
// ERROR!
}
}
function initRequest(request,type,url,asynch,respHandle) {
try {
respHandle.setReqObj(request);
request.onreadystatechange = respHandle.goResponse;
request.open(type,url,asynch);
if (type.toLowerCase() == "post") {
request.setRequestHeader(
"Content-Type",
"application/x-www-form-urlencoded; charset=UTF-8"
);
request.send(arguments[5]);
} else {
request.send(null);
}
} catch (errv) {
// ERROR!
}
}
Function D (callback):
function ReturnSaveTag() {
var reqObj = null;
this.setReqObj = setReqObj;
this.goResponse = goResponse;
function setReqObj(myVal) { reqObj = myVal; }
function goResponse() {
var request = reqObj;
if (request.readyState == 4) {
if (request.status == 200) {
// Success!
var mytext = request.responseText;
// Here, do normal UI stuff... e.g.,
var jsonObject = eval('(' + request.responseText + ')');
document.getElementById("tag_box").innerHTML = jsonObject.tag;
} else {
// ERROR (couldn't find ajax file)
}
}
return true;
} // end method
}
8 months ago