简体   繁体   中英

Execute a function after two (or more) ajax request succeed

I need to perform two independent ajax requests and a function to be executed after both of them succeed. I can obviously send the first request, then send the second one when the first one succeeds and finally execute the function when the second request succeeds. But is there a way to execute them separately and execute the function when both of them succeed?

ie I could have the following requests:

var jqxhr1 = $.post( "example1.php", function() {
  alert( "first success" );
})
var jqxhr2 = $.post( "example2.php", function() {
  alert( "second success" );
})

and the following function:

function myfunction() {
  alert( "function success" );
}

As many commented under your question the best way is to use Promises. As I see you are using jQuery so I will post you my answer using jQuery. So the basic setup will be:

html :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>

<button id="one">Send 2 ajax</button>

<script src="script.js"></script>
</body>
</html>

example1.php :

<?php
echo json_encode($_POST['button']);

example2.php :

<?php
sleep(5);
echo json_encode($_POST['button']);

And javascript file:

$( document ).ready( function () {

    var $button1 = $( '#one' );

    $button1.on( 'click', function ( e ) {
        e.preventDefault();

        $.when(
            $.ajax( {
                url: "example1.php",
                type: "post",
                data: { button: "some data" }
            } ),
            $.ajax( {
                url: "example2.php",
                type: "post",
                data: { button: "some data" }
            } ) ).done( function ( a1, a2 ) {
            console.log( a1 );
            console.log( a2 );
        } );

    } )

} );

Explanation : $.when() is used when you want to wait until several ajax request are successful. So in my example done() is executed after 5 seconds when two ajax request are successful. First and second params is returned values from first and second ajax call. You can read more about it in link I provided above. Returned data is like this:

Array[3]
    0:""Some data from AJAX 1""
    1:"success"
    2:Object
    length:3
    __proto__:Array[0]

Array[3]
    0:""Some data from AJAX 2""
    1:"success"
    2:Object
    length:3
    __proto__:Array[0]

example1.php and example2.php are very simple - they just send json back to javascript. Except that example2.php simulates ajax response timeout of 5 seconds.

PS : Code above is working example, which I'm running on my local machine.

You just need to use $.when In the case where multiple Deferred objects

var jqxhr1 = $.post( 'example1.php');
var jqxhr2 = $.post( 'example2.php');

$.when(jqxhr1, jqxhr2).then(function( response1, response2 ) {
   console.log('both requests succeed, do staff here')
});

Hope this will be helpful.

You can declare a variable called requestsCompleted and asign it a value of zero. Every time a request is completed, add 1 to the variable, and when its equal to two, execute the function

Edit: As @Pogrindis pointed out, the best way is to use Promise.all() ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all )

Just use something like this:

 var count = 0;

    while (count < 2){
     //do ajax call
         //on success increment counter
         //on error just log and continue

    //you can put a timeout here and just do 'return' after if you wish
    }

    functionCall();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM