views:

216

answers:

9

I have a JavaScript function that makes two consecutive Ajax requests using jQuery. I want to make sure that the first request has loaded before the second function is called. Is there a way I can do this?

A: 

In your callback for the first function, make your second call.

Daniel A. White
+4  A: 

Either specify async: false in the $.ajax options, or make the second ajax call in the complete callback of the first call.

Stefan Kendall
Wouldn't that be `async: false`?
TM
Indeed it would. Darn that negative logic.
Stefan Kendall
`async: false` works great. The order in which I call the two functions varies, so it's much preferred to the callback method.
Brian
A: 

Use the callback parameter in the first Ajax call to call the second function.

sberry2A
A: 

For best results you should probably invoke the second function in the callback of the first.

For Example:

$.post("http://www.somewebsite.com/page.php", function(data) {
  // whatever
  function2();
});
Nathan Taylor
A: 
$.post("script1.php", {data:"val"}, function(response) {
  $.post("script2.php", {data:response}, function(results) {
    // this second call will be initialized when the first finishes
  });
});
Jonathan Sampson
A: 

An example implementation:

function callback() {$('div#second_ajax_output').load('http://www.google.com');}
$('div#first_ajax_output').load('http://www.yahoo.com',callback);
Steven Xu
A: 

Edit: Misread the question; my bad. If you ever want to have two AJAX requests executed concurrently but run a callback only after both have finished, this is how you do it!

Try this:

var completedCount = 0;
var callback = function()
{
    completedCount++;
    if (completedCount == 2)
    {
        // Do something.
    }
};

$.post('url-1', {}, callback);
$.post('url-2', {}, callback);
Will Vousden
A: 

Using jQuery the simplest way is like this:

 $.ajax({
   type: "POST",
   url: "some.php",       
    success: function(msg){
       $.ajax({
         type: "POST",
         url: "some2.php",

         success: function(msg){
             alert( "End of second call" );
         }
      });
    }
 });
Vincent Ramdhanie
A: 

The simple way is to fire the second request when the first returns (in the complete callback).

If you need a more sophisticated approach take a look at the AjaxQueue plug-in. You can queue requests this way.

cletus