Definitely, Asynchronous JavaScript and XML (AJAX) is the new buzzword of the Internet with more and more websites using it. This is a technology based on XMLHttpRequest object to exchange data asynchronously with a web server, available in all modern browsers. The result is quite interesting: you can update parts of the web page without re-loading the entire page. You can change dynamically webpages based on user interaction.
As this technology is named, everything is asynchronous: a request is made and a callback function is declared, which is called during the process and at the end of the request. Nothing about synchronous operations, this object supports.
Asynchronous operations are very good with lengthy requests, when user is not blocked till the request is processed. You can display an animated images to let user know that is working, and the whole process is made in the background. All AJAX is based on this idea. But there are times when user is only waiting for response, usually short response, just to process small amounts of data. In this case more logical is a synchronous operation, still available with XMLHttpRequest.
For details how to use XMLHttpRequest see this interesting article: Dynamic HTML and XML: The XMLHttpRequest Object. In this example is used an asynchronous call (see processReqChange() callback function). Let’s change it synchronous:
var req;
function loadXMLDoc(url) {
req = false;
// branch for native XMLHttpRequest object
if(window.XMLHttpRequest) {
try {
req = new XMLHttpRequest();
} catch(e) {
req = false;
}
// branch for IE/Windows ActiveX version
} else if(window.ActiveXObject) {
try {
req = new ActiveXObject(”Msxml2.XMLHTTP”);
} catch(e) {
try {
req = new ActiveXObject(”Microsoft.XMLHTTP”);
} catch(e) {
req = false;
}
}
}
if(req) {
req.open(”GET”, url, false);
req.send(”");
return(req.responseText);
}
}
Then you can use it simply: alert(loadXMLDoc(’local_file.htm’))
Changes are minor: only pass ‘false’ as third parameter for open() and you don’t need a callback function. Everything happens synchronously: user make a request and wait for its response.
Very important is security limitation, in all browsers: you can’t access files from another domains, because of the ’sandbox’ policies. But you can access files from the same server (maybe you can build a page to load other URLs server-side).
The only thing I want to highlight here is that it may be times when synchronous process is enough and simpler. Is this AJAX or SJAX?