using the XMLHttpRequest
with all the emerging web applications out there, ajax has come overwhelmingly popular as a means to have active content on a page update without the need to re-load. one of the easiest way to achieve this is to use the XMLHttpRequest.
i have stated before that i am not an advocate of writing browser detection scripts since it makes more sense to check for the appropriate method when carrying out a task. in order to achieve this with the XMLHttpRequest is quite simple: write a function that attempts to create an XMLHttpRequest a number of ways and returns the results on success or an error on failure.
the function:
function new_request() {
if (typeof XMLHttpRequest != "undefined") {
return new XMLHttpRequest();
} else if (typeof ActiveXObject != "undefined") {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
throw new Error("XMLHttpRequest not supported");
}
}
simple enough right? now whenever you need to make an XMLHttpRequest a few lines of code will get the information you need
using the function:
var url = "/my_file"; // the path to the file you want to use
var request = new_request();
request.open("GET", url, true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
// the code you want to run when the file/data is loaded
}
}
XMLHttpRequest can return two forms of data: xml dom object and text. this means, depending on what you ask it to do withing the request.readyState == 4 statement, you will be given a certain type of data. if you are simply making a call to a text file that contains a paragraph and you want to display that paragraph you would use the following code:
var txt = request.responseText
while this can be usefull if you have many small txt files that make up the content of a page, i feel it is infinitely more powerful to store the same data in an xml file and just traverse the file to get the data you need from it. to do this you would use the following line instead:
var xmlDoc = request.responseXML
this would allow you to work with the xml dom to pull values out of the file as you need them. so the full code to bring the data in would be the following:
var url = "/my_file.xml"; // the path to the file you want to use
var request = new_request();
request.open("GET", url, true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
// the file will be read in as an xml dom object
var xmlDoc = request.responseXML;
}
}
you can now traverse the xml dom object to get whatever data you need out of the file. i will be writing instructions on how to traverse the xml dom in another post so this is where i will end.




