views:

325

answers:

2

Requirement : I have a piece of code similar to the code below. I want to show a progress bar in an overlay after the save button is clicked. Once I get the response from the ajax call, I show an alert displaying that the operation was successful.

Issue : The overlay ( progress bar) is visible only after we have got the response from the ajax call and we display the alert. It is not visible while the ajax call is getting processed.

Am I doing something wrong here or is this the expected behavior? I am using pure javascript. I cannot use any external library to do this.

<script>
  function save(){
      document.getElementById('overlaydiv').style.display = 'block';
      document.getElementById('progressBarDiv ').style.display = 'block';
      var URL = 'some url';
      ajaxFunction(URL, false);
  }
  function ajaxFunction(URL, isAsynchronousCall){
      var xmlHttp;
      var callTypeFlag = true; // is an Asynchronous Call
      if(isAsynchronousCall != null){
         callTypeFlag = isAsynchronousCall;
      }
      try{
          if (window.XMLHttpRequest) {
            xmlHttp = new XMLHttpRequest();
          } else if (window.ActiveXObject) {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
          }
      }catch (e){
         alert("Your browser does not support AJAX!");
         return false;
      }
      xmlHttp.open("GET", URL, callTypeFlag);
      xmlHttp.onreadystatechange = function(){responseProcessor(xmlHttp)};
      xmlHttp.send(null);
   }
   function responseProcessor(xmlHttp){
    //If the readystate is 4 then check for the request status.
      if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
            alert('Settings saved successfully');
            window.close();
            opener.location.href='new URL';
         }
       }
   }
</script>

<div id="overlaydiv" style="display:none"/>  
<div id="progressBarDiv" style="display:none">
  <img border="0" src="progressBar.gif"/>
</div>
<div>
 <table>
   <tr>
     <td>
       <input type="button" onclick="save()"/>
     </td>
   </tr>
 </table>
</div>
+1  A: 

Put a little delay when calling ajaxFunction()

function save(){
      document.getElementById('overlaydiv').style.display = 'block';
      document.getElementById('progressBarDiv ').style.display = 'block';

      setTimeout(ajaxFunction, 50);//5,10,20,30,40 will do
}
jerjer
The setTimeOut solution is not working.
Deepak Singh Rawat
A: 

It appears the issue was because I was using synchronous ajax call. I changed the call to asynchronous and now there is no issue.

Deepak Singh Rawat