Thursday, November 11, 2010

Load time animation for AJAX

While using AJAX for fetching data there is always a lag (as there is for any other data request). More importantly, as this request happens behind the scenes, meaning that the page is not refreshed, the user is sometimes unaware of the data pull. A rule of thumb is to show an animation or at least some text which indicates user that data is being fetched. This can be achieved as follows:

Your AJAX function:

function ajax_request(url, target){ //url -> URL of the file that will provide the requested data, target -> the div or span element that displays the data
....code to check the HTTP status and until it is 200 and the readyState is 4 do:

document.getElementById(target).innerHTML = ' Fetching data...';
OR
document.getElementById(target).innerHTML = '../path-to-image/';

....code to perform action upon status/state change
}

A good resource to find free-to-use gif loading animations is: http://www.ajaxload.info/

No comments:

Post a Comment