1

A function uses the jquery.ajax() method to get data from server and use it as return value. If I use async=true the function returns prematurely empty value. If I use async=false the wait for the function is too long. I tried toggle div showing spinning clock right before the request, but the div does not appear until the request is over.

Any advice on how not to lock the browser or show wait icon/symbol/text?

Shog9
  • 156,901
  • 35
  • 231
  • 235
selytch
  • 535
  • 2
  • 9
  • 24

3 Answers3

2

You can't. Synchronous requests will lock up the browser, including any animations you might have going or dom modifications that might be pending - that's why they're discouraged. Chances are, you're trying to return a value from the function firing off the ajax request, which WILL NOT WORK for async requests - modify your logic to handle the response processing in the success callback, and all will be well...

Shog9
  • 156,901
  • 35
  • 231
  • 235
  • any good resources on jquery handling async response from PHP mysql query? – selytch Aug 02 '10 at 07:08
  • @selytch: it's nothing specific to PHP or MySQL; it's how asynchronous calls must *always* be handled: everything you want to happen after the call needs to be triggered from the callback. See: http://stackoverflow.com/questions/2851952/jquery-ajax-function-to-call-php-script-which-returns-a-value or http://stackoverflow.com/questions/31129/how-can-i-return-a-variable-from-a-getjson-function or http://stackoverflow.com/questions/402503/ajax-return-data-not-working-in-jquery ... – Shog9 Aug 02 '10 at 15:51
1

For not locking the browser you should use async request, maybe your code or ajax response needs refactoring.

But if you still not wanting to use async requests, you can do something like this:

  1. Insert the spinning clock and show
  2. When ready (and I mean a callback), make the ajax request
  3. Finally, remove the clock
alcuadrado
  • 8,340
  • 3
  • 24
  • 25
  • Server responds with JSON object, which I understand (correct me if I'm wrong), requires SYNC. I also have hard time planning how to handle ASYNC response for array of objects... If I put $('#wait').show('fast',function () {$.ajax ....}) browser (Chrome) still refuses to show the #wait until request is complete. – selytch Aug 02 '10 at 05:05
  • I've used json many times with the default async mode. I don't see why it needs to be synchronous. – Benbob Aug 02 '10 at 05:53
1

one way is to put an image (Loading... gif animated). Show it before you send the ajax. Then hide it on success. Just like below.

$.ajax({
  url: 'ajax/test.html',
  beforeSend : function(){
     $('#LodingImg').show(); // show image..
  },
  success: function(data) {
    $('#LodingImg').hide(); // hide image
    $('.result').html(data);
    alert('Load was performed.');
  }
});
Reigel Gallarde
  • 64,198
  • 21
  • 121
  • 139