thedigitalfeed.co.uk content
thedigitalfeed.co.uk/Code
AJAX: Nice and Easy
Posted on Tuesday the 24th of January, 2006
www.thedigitalfeed.co.uk/code/2006/01/24/ajax-nice-and-easy
First, we have to find a valid XMLHttpRequest for the User Agent. Because XMLHttpRequest is a non-standard function, each browser handles it differently. That is, IE handles it differently to anything else :)
var request = false;
// find a valid XMLHttpRequest
try {
request = new XMLHttpRequest();
}
catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (failed) {
request = false;
}
}
}
if (!request)
// Alert the user if XMLHttpRequest doesn't exist.
alert("Error initializing XMLHttpRequest.\n" +
"You may need to enable Javascript in your browser.");
See that we're calling a basic XMLHttpRequest first. If that fails, then we'll fall back to IE's methods. With any luck, now we'll have a new request to work with. If not, we alert the user that they'll need to at least have Javascript enabled to use this functionality.
The next step is to add a function to take data and pass it to a script on the server. This function will be called by some Javascript on the client. I've made it fairly abstract, and have only coded in the script URL because I'm only using it for my help system.
function getData(k,v) {
// pass a key and a value over to the script
var url = "info.php?"+k+"=" + escape(v);
request.open("GET", url, true);
request.onreadystatechange = updatePage;
request.send(null);
}The server script looks for specific key and builds a different SQL query based on that. This is so that I can build both direct links (key='name') and a search function (key='keywords').