8

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?

Brian
  • 26,662
  • 52
  • 135
  • 170
  • 1
    Is it the second *Ajax* call that needs to wait until the first one has returned, or the second *callback* that needs to wait? (i.e. do you need to wait before firing off the second ajax request, or can both be fired off one after the other, but you want to make sure that if the second one returns first, its callback is blocked until the first one returns) – Graza Jan 04 '10 at 23:34
  • The 2nd function should not be fired until the first has completed. The 1st function creates a form element and the 2nd takes that form value and makes some calculations based on it. – Brian Jan 04 '10 at 23:43

9 Answers9

9

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

Stefan Kendall
  • 66,414
  • 68
  • 253
  • 406
1
$.post("script1.php", {data:"val"}, function(response) {
  $.post("script2.php", {data:response}, function(results) {
    // this second call will be initialized when the first finishes
  });
});
Sampson
  • 265,109
  • 74
  • 539
  • 565
1

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
  • 102,349
  • 23
  • 137
  • 192
0

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

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
0

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
  • 24,423
  • 19
  • 99
  • 156
0

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
  • 17,796
  • 13
  • 66
  • 118
0

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
  • 616,129
  • 168
  • 910
  • 942
0

Since jQuery requests return thenables, in modern browsers, you can await each call. For example:

async function fetchBoth() {
  const todo1 = await $.get('https://jsonplaceholder.typicode.com/todos/1');
  const todo2 = await $.get('https://jsonplaceholder.typicode.com/todos/2');
}

fetchBoth();

async function fetchBoth() {
  console.log('start 1');
  const todo1 = await $.get('https://jsonplaceholder.typicode.com/todos/1');
  console.log('got todo1', todo1);
  console.log('start 2');
  const todo2 = await $.get('https://jsonplaceholder.typicode.com/todos/2');
  console.log('got todo2', todo2);
}

fetchBoth();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Don't use async: false. Synchronous ajax requests are deprecated and should not be used; if used, users will probably see console warnings as a result.

Note that this use of await works just fine for any sort of Promise, not ajax requests, and not just jQuery. For example:

async function fetchBoth() {
  console.log('start 1');
  const todo1 = await fetch('https://jsonplaceholder.typicode.com/todos/1').then(res => res.json());
  console.log('got todo1', todo1);
  console.log('start 2');
  const todo2 = await fetch('https://jsonplaceholder.typicode.com/todos/2').then(res => res.json());
  console.log('got todo2', todo2);
}

fetchBoth();
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
-1

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
  • 32,488
  • 9
  • 84
  • 95