Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery ajax synchronous call beforeSend

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?

like image 289
Daniel Avatar asked Feb 11 '11 15:02

Daniel


2 Answers

When you do the blocking I/O the program is halted until the the input is received, in JS words when doing a synchronous call, the program halts and browser window freezes (no painting can be done) until the response is received. In most cases doing syncronus calls and any kind of blocking I/O can be avoided. However imagine your doing a progress bar in java or any other programming language, you have to spawn a different thread to control the progress bar, I think.

One thing to try in your case, is to call the ajax call after a time delay

//loading div stuff, 
//if your doing some animation here make sure to have Sufficient 
//time for it. If its just a regular show then use a time delay of 100-200
setTimeout( ajaxCall, 500 );

EDIT ajaxcall in setTimeout, Example

like image 172
Amjad Masad Avatar answered Sep 17 '22 12:09

Amjad Masad


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.

like image 45
Pointy Avatar answered Sep 20 '22 12:09

Pointy