The Flicker-Less Web: Mastering AJAX with XMLHttpRequest and JSON
In 2006, the term 'AJAX' (Asynchronous JavaScript and XML) is everywhere. Jesse James Garrett coined it last year, but this year, it's how we build real software. No more 'click and wait' while the whole browser window flickers white and reloads. We're building apps like Gmail and Google Maps, where the UI stays live and the data flows in the background.
The engine of this revolution is the XMLHttpRequest object. And while the 'X' stands for XML, the real power users are already moving to something much lighter: JSON (JavaScript Object Notation).
Making the Request (The IE6 Hurdle)
In a perfect world, we'd just use new XMLHttpRequest(). But in 2006, Internet Explorer 6 still rules the market, and it uses an ActiveX object.
function getXHR() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
// Handle IE6/IE5.5
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
var xhr = getXHR();
xhr.open("GET", "/api/get_updates.php", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// Success! Handle the data
updateUI(xhr.responseText);
}
};
xhr.send(null);
JSON: The 'XML Killer'
XML is verbose and slow to parse in the browser. JSON is just a string that looks like a JavaScript object. This means we can "parse" it using the eval() function-though you must be careful about security.
// Response from server: '{"status": "ok", "items": ["Item A", "Item B"]}'
function updateUI(responseText) {
// In 2006, we use eval(). Native JSON.parse is still years away.
// Wrap the string in parentheses to make it a valid JS expression.
var data = eval('(' + responseText + ')');
var list = document.getElementById('update-list');
for (var i = 0; i < data.items.length; i++) {
var li = document.createElement('li');
li.innerHTML = data.items[i];
list.appendChild(li);
}
}
The 'Spinning Wheel' and User Experience
With AJAX, the browser gives no visual indication that something is happening. If you don't show a 'loading' indicator (the classic spinning wheel), the user will think your site is broken. Always hook into the onreadystatechange to toggle your loading state.
One of the biggest pitfalls of the Web 2.0 era is the 'Broken Back Button'. Since the URL doesn't change when you load data via AJAX, clicking 'Back' takes the user off your site entirely instead of undoing their last action. We're experimenting with window.location.hash (the part after the #) to track state, but it’s still a bit of a hack.
The goal is to build a web that feels like a desktop application. If your site still has a 'Submit' button that causes a full page reload, you're not building for 2006.
Aunimeda builds modern web frontends - from single-page applications to complex multi-locale sites.
Contact us to discuss your frontend project. See also: Web Development, Corporate Website Development