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/

Thursday, November 4, 2010

UTF-8 characters get garbled in AJAX response

This problem is often experienced in websites dealing with multiple languages and special characters. Characters are unicode characters and there are many ways in which they can be encoded. UTF-8 is just one way of the ways of doing it.

Consider an AJAX request that fetches HTML text from a database:

xmlhttp.open("GET","get_html.php",true);

The response to this request could possibly contain special characters (entered through a WYSIWYG editor) which will get rendered as "junk" characters as there is no natural way for the response to know the encoding. As a result the output fetched by the response needs to be encoded. One of the ways of getting HTML text rendered correctly in an AJAX response is by encoding it using utf8_encode() and then using html_entity_decode() as follows:

//code to fetch response data from db into a var, say $db_data
$utf8_encoded_char = utf8_encode($db_data);
$html_text = html_entity_decode($utf8_encoded_char);

Hello WWW!

Hello readers and fellow web developers,

Welcome to Spider-Eye - the blog dedicated to providing solutions to challenges encountered in website development. Every day I come across some interesting problems and many a times the solutions get lost into oblivion once I have moved past those problems. I am sure the same happens with most of the other web developers as well.

Through this blog, I look forward to interacting with you and sharing my insights and breakthroughs in web development. Here's to building better websites!

Cheers,
Tejas