View Full Version : Loading icon - when should it be displayed

12-24-2008, 12:10 PM
OK, I'm an AJAX newbie, and I just had a quick question.

My goal is to have a loading icon appear and disappear while an xmlhttprequest is being executed. My question is, when should I make the loading icon appear and disappear. I know this may seem trivial, but I just wanted to clarify the timeline of an AJAX request.

Should its dis/appearance be dependent on ready state changes, or should it bet dependent on when functions are executed?

When should I make the div which contains the loading icon visible?
a. When the open() function is invoked
b. When the send() function is invoked
c. When the readystate changes to 2
d. When the readystate changes to 3

I assume I should make it disappear when the readstate changes to 4, but is that correct?

Sorry for the barrage of questions, just wanted to get some clarity on this.

12-24-2008, 03:44 PM
if (readystate!=4)
// show the loading icon
else if(readystate==4)
// hide the loading icon

01-01-2009, 07:01 AM
Also an AJAX newbie here.....

I'm using something like this to implement the info. that was just retrieved. I assume that it will check the readyState as it moves through each value up to when it ==4?

if (xmlHttp.readyState!=4)
// show the loading icon

else if(xmlHttp.readyState==4)
// hide loading icon
do something;

01-16-2009, 12:50 AM
I'm doing the above but i've got an issue. I'm trying to have a button to show comments about a news article, so when the user clicks "Show Comments" it shows the loading image and then the comments, which is fine. However if I then click to see another new stories comments the previous one just displays the loading image and removes the comments that where there.

The code is:

if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
//mystr completes the div id e.g. comments2 or comments3 etc.
txtloc = "comments" + mystr;
document.getElementById(txtloc).innerHTML = xmlHttp.responseText;
document.getElementById(txtloc).innerHTML = "<img src='images/loading.gif' />";

Sorry if this is a stupid mistake on my part but I'm baffled!

01-16-2009, 05:16 AM
It is because you are replacing the innerHTML.

If you do not want to remove the data, you need to find a new way to add the image to the page. Your best bet would be to hardcode the image tag on the page and set it to hidden. When you need it to show you set it to be visible.