Make sure the first ajax function ends before the second

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

+6
javascript jquery ajax
source share
8 answers

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

+7
source share

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

0
source share

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

Example:

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

Implementation Example:

 function callback() {$('div#second_ajax_output').load('http://www.google.com');} $('div#first_ajax_output').load('http://www.yahoo.com',callback); 
0
source share

Using jQuery in the simplest way looks 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" ); } }); } }); 
0
source share

A simple way is to run a second request on the first return (in a full callback).

If you need a more sophisticated approach, take a look at the AjaxQueue plugin. You can request queues this way.

0
source share

Edit: Ignore the question; my fault. If you ever want two AJAX requests to be executed at the same time, but only call back after both are complete, here's how you do it!

Try the following:

 var completedCount = 0; var callback = function() { completedCount++; if (completedCount == 2) { // Do something. } }; $.post('url-1', {}, callback); $.post('url-2', {}, callback); 
-one
source share

All Articles