I have a web application that for one reason or another I'm currently unable to utilize AJAX to enable a nice, seamless, and seemingly postbackless experience. I've maintained this particular application for several years now and it has a lot of AJAX-y like behaviors, but much of it feels like a hack and is somewhat unwieldy. This particular application is (currently) specific to IE 6.0+.
I'm not going to wax too technical here since I want to keep this really light, but since IE 5.0 Microsoft has made a nice little COM object called Microsoft.XMLHTTP that allows a developer to submit http requests to a server and act on the results. This is quite easily accomplished via Javascript on the client, as the following code demonstrates:
var http = new ActiveXObject("Microsoft.XMLHTTP");
http.onreadystatechange = function() {
if ( 4 == http.readyState ) {
// process the resulting response
alert(http.responseText);
}
};
http.open("POST", "http://someurl/here", true);
http.send("");
There's really nothing too it - and there's tons out there online that illustrate how to do this and I'll leave it to you to research it if you need to. The above code, however, leaves something to be desired: the way it's structured, I cannot reuse the XMLHTTP object - well, technically, I can, but my onreadystatechange event won't fire the second time. I don't want to have to recreate an XMLHTTP instance for each and every request - I want to reuse the instance I already have.
This is easily solved by setting the onreadystatechange event after the call to the .open() method as such:
var http = new ActiveXObject("Microsoft.XMLHTTP");
function post(request) {
http.open("POST", "http://someurl/here", true);
http.onreadystatechange = function() {
if ( 4 == http.readyState ) {
// process the resulting response
alert(http.responseText);
}
};
http.send(request);
}
Now I've isolated the request portion into a method that I can call repeatedly and act on the results accordingly.
Simple.