views:

169

answers:

3

Similar to the question I just asked,

If I call an ajax function in jQuery and then a non ajax function how can I prevent the non-ajax function from firing until after the first ajax callback function has completed. Will declaring async: false in the first ajax function be enough?

+1  A: 

jQuery AJAX functions let you provide a callback that is only called after the request is finished. Call your non-ajax function as part of that callback.

Victor Nicollet
A: 

Similar to the answer I posted, I would just use the callback parameter in the ajax call to handle the second function call. For example:

$.post("myScript.py", myData,
  function(response){
    callOtherFunction();        
  }, "json");
sberry2A
I have several functions that I use in different orders throughout the page. Placing in the callback would work, but would force me to create a new set of functions for each sequence. I am looking for a cleaner solution if possible.
Brian
+4  A: 

If you're talking about this:

$.ajax({...});
someFunction();

where someFunction() won't occur until the AJAX call completes then you have three options:

  1. Make the AJAX call async: false. Don't do this. It'll make your page unresponsive;
  2. Put someFunction() in the complete/success/error callbacks of the AJAX call. This is the recommended approach; or
  3. Use aplugin to manage a request queue eg Ajax Queue.

The first A in AJAX stands for "asynchronous". You just need to get used to the fact that these calls are asynchronous and stop trying to force a synchronous programming model on top of them. Adapt to the new programming model.

cletus
what's so bad about `async: false`?I used it before and it seems ok
Brian
Because while the request is happening the page (and the whole browser if you're not using Chrome) will lock up. If this is 100ms or less it probably won't be noticeable but if the request gets delayed, there are network issues or the server process is reasonably long-running this is going to be a huge problem.
cletus
It seems like chaining callback functions also causes the browser to lock up. Is there a way around this?
Brian