Javascript – jquery ajax synchronous call beforeSend

ajaxjavascriptjquery

I have a function called:

function callAjax(url, data) {
 $.ajax(
   {
     url: url, // same domain
     data: data,
     cache: false,
     async: false, // use sync results
     beforeSend: function() {
       // show loading indicator
     },
     success: function() {
       // remove loading indicator 
     }
   }
  );
}

In the code, I call "callAjax" X number of times and I want to update the data synchronously. It is done as expected, but one problem: the loading item doesn't show in beforeSend function. If I turn async to true, it works but the updates aren't synchronously done.

I've tried several things with no success. I tried putting the loading indicator before the ajax call like this:

function callAjax(url, data) {
  // show loading div

  $.ajax(
    {
      // same as above
    }
   );
}

But for some reason it doesn't want to show the loading indicator. I notice a strange behavior when I put an "alert" in the beforeSend and the loading indicator appears in that case, but I rather not pop up a message box.

Got any ideas?

Best Answer

Making a synchronous call like that is like putting up an "alert()" box. Some browsers stop what they're doing, completely, until the HTTP response is received.

Thus in your code, after your call to the "$.ajax()" function begins, nothing happens until the response is received, and the next thing as far as your code goes will be the "success" handler.

Generally, unless you're really confident in your server, it's a much better idea to use asynchronous calls. When you do it that way, the browser immediately returns to its work and simply listens in the background for the HTTP response. When the response arrives, your success handler will be invoked.