Showing a 'Please Wait' Message to Users

 

When your Ajax call asks something complicated of the server, it may take a moment or two for the server to come back with the answer. Since Ajax applications do not necessarily have page loads associated with server activity, it may not be obvious to the user that anything is happening.

 

It is, thankfully, a straightforward task to display a message or an image to the user to make it clear that (s)he should wait a moment longer. Let's revisit the callback function from the previous tutorial:

function handleHttpResponse() {
if (http.readyState == 4) {
    var data_returned = http.responseText;
      //  ... we can process this however we please ...
   }
}

This code waits until the readyState property of the XMLHTTPRequest object reaches 4 (indicating that the call has completed). All previous states are ignored. However, it's easy to add a little more code on the end to make a DIV element visible while we are waiting for the completed state to occur:

function handleHttpResponse() {
if (http.readyState == 4) {
   document.getElementById('wait').style.visibility = "hidden";
    var data_returned = http.responseText;
      //  ... we can process this however we please ...
  } else {
      document.getElementById('wait').style.visibility = "visible";
  }
}

Let's assume we have a DIV element with id="wait" and initial visibility set to hidden. After initiating the XMLHTTPRequest object, the initial values of the object's readyState property (i.e. values less than 4) will cause the else clause to be executed, making the DIV visible. When the readyState reaches 4, the DIV will once more be hidden, and the rest of the callback function then carried out.

 

Try the example here



This site is brand new and so still somewhat under construction.

Why not bookmark it and call back regularly?

Related:

Links: