Synchronize three ajax requests
Asked Answered
R

1

7

I have three AJAX requests firing one after another, and I'd like to be able to echo back all the data simultaneously.

$.ajax ({
        type: "POST",
        url: "page1.php",
        data: "var1=" + var1,
        success: function(msg) {
            $("#results2").load("page2.php", 
            function (responseText, textStatus, XMLHttpRequest) {
                $("#results3").load("page3.php",
                function (responseText, textStatus, XMLHttpRequest) {
                    if (textStatus == "success") {
                        $("#results1").html(msg);
                    }
                });
          });
        }
    });

#results1, #results2 and #results3 all need to be loaded with their relative data at the same time. The above code isn't doing it.

Rugen answered 7/2, 2012 at 10:3 Comment(0)
L
10

you can use deferred object of jQuery added in 1.5 version:

$.when( $.ajax({1}) , $.ajax({2}) , $.ajax({3}) )
.then(function() {
  alert("tada");
});
Lexicon answered 7/2, 2012 at 10:10 Comment(1)
yes, deferred object are very power and improve code readabilityFetching

© 2022 - 2024 — McMap. All rights reserved.