Search code examples
javascriptasynchronousxmlhttprequestxdomainrequest

Waiting for two asynchonous requests


I'm having trouble sending two request in PHP and waiting for both answers. Here is my code :

        function getXDomainRequest() {
            var xdr = null;

            if (window.XDomainRequest) {
                xdr = new XDomainRequest();
            } else if (window.XMLHttpRequest) {
                xdr = new XMLHttpRequest({mozSystem: true});
            } else {
                alert("Your browser does not support AJAX");
            }

            return xdr;
        }

        function sendData() {
            var json1= "";
            var json2= "";

            var xdr = getXDomainRequest();
            xdr.onload = function() {
                json1 = xdr.responseText;
            }

            var xdr2 = getXDomainRequest();
            xdr2.onload = function() {
                json2 = xdr2.responseText;
            }

            var Id = document.querySelector('#searchField').value;
            // Call API
            xdr.open("GET", "./dorequest.php?id=" + Id + "&requesttype=player");
            xdr.send();

            xdr2.open("GET", "./dorequest.php?id=" + Id + "&requesttype=stats");
            xdr2.send();

            xdr.wait();
            // Display results
            getHtmlResults(jsonPlayer, jsonStats);
        }

As expected here the json1 and json2 are still empty when getHtmlResults is called. I could do it synchronously by calling the xdr2.send() into the xdr.onload and my final function in the xdr2.onload but I want to do it asynchronously to get a better response time.

Thanks !

(any other comment on the code is welcome I'm quite new to php :) )

EDIT :

So I tryied using Ajax and it seems to work :)

            var jsonPlayer = "";
            var jsonStats = "";
            var steamId = document.querySelector('#searchField').value;
            $.when(
                $.ajax({url: "./dorequest.php?steamid=" + steamId + "&requesttype=playersummary",
                        success: function(response){ jsonPlayer = response; }}),
                $.ajax({url: "./dorequest.php?steamid=" + steamId + "&requesttype=csgostats",
                        success: function(response){ jsonStats = response; }}) ).done(
                function(player, stats) {
                            getHtmlResults(player, stats);
                        });

Solution

  • Promises are commonly used as an abstraction to deal with asynchronous processes.

    Wrap your AJAX calls in a Promise to do:

    var ajax1 = request("stats");
    var ajax2 = request("player");
    when(ajax1, ajax2).done(function (stats, player) {
        console.log(stats, player);
    });
    

    Most popular frameworks have a built-in Promise API.