Search code examples
javascriptjqueryajaxasynccallback

execution out of order inside ajax callback function javascript


I have a following ajax operation that is intended to (1) show spinner gif before sending ajax request, and after after the request is complete, (2) hide the gif and 3 display appropriate alert messages. Finally (4) reload the page.

Here's the code:

$.ajax({
   url: rUrl,
   data: {
      id: rID,
      requisitionStatus: rStatus,
      comment: rComment
   },
   type: "POST",
   cache: false,
   beforeSend: function() {
      $("#requisitionStatusDialog").dialog('close');
      $('#ajax_loader_my').show();
   },
   success: function(data, resp) {
      var json = data;
      var obj = JSON && JSON.parse(json) || $.parseJSON(json);
      if (obj.status == "success") {
         alert('Success! ' + obj.message);
         location.reload();
      } else if (obj.status == "error") {
         alert('Error!' + obj.message);
      }
   },
   error: function(data, resp) {
      $("#updateDialog").dialog('close');
      console.log(resp);
   },
   complete: function() {
      $('#ajax_loader_my').hide();
   }
});

But in this case, alert pops up first while the spinner gif still shows up, and reloads the page after clicking OK.

I even tried hiding the gif in success callback itself instead of using complete:

success: function(data, resp) {
  var json = data;
  var obj = JSON && JSON.parse(json) || $.parseJSON(json);
  if (obj.status == "success") {
     $('#ajax_loader_my').hide();
     alert('Success! ' + obj.message);
     location.reload();
  } else if (obj.status == "error") {
     alert('Error!' + obj.message);
  }

},

Both gives the same result.


Solution

  • Rewrite the code this way, this will put your alert and location related code in event queue which will run when it will be free.

    if(obj.status=="success") { 
          $('#ajax_loader_my').hide(); 
          setTimeout(function(){
              alert('Success! '+obj.message);
              location.reload();
          },0);
    }