views:

59

answers:

1

Is it possible to send Ajax requests to two or more Php scripts simultaneously? I know that this can be achieved serially (getting response from 1 and then getting response from the other) but I am wondering is it possible simultaneously. Please assist me with the following code:

function calShowUpload(){
    if (http.readyState == 4) {
        res = http.responseText;
        document.getElementById('maincontent').innerHTML=res;
    }
}

function showUpload(obj)
{
      http.open("GET", "./showUpload.php", true);
    http.onreadystatechange = calShowUpload;
    http.send(null);
}


function getXHTTP() {
    var xhttp;
    try {   // The following "try" blocks get the XMLHTTP object for various browsers…
            xhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } 
    catch (e) {
            try {
            xhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } 
        catch (e2) {
         // This block handles Mozilla/Firefox browsers...
                try {
                    xhttp = new XMLHttpRequest();
                } 
            catch (e3) {
                    xhttp = false;
                }
            }
        }
    return xhttp; // Return the XMLHTTP object
}

var http = getXHTTP(); // This executes when the page first loads.

In the above example I know that I can call another function like showUpload(obj) inside calShowUpload() to achieve my objective, but I need something like this:

function showUpload(obj)
{
      http.open("GET", "./showUpload.php", true);
      http.open("GET", "./showDelete.php", true);
    http.onreadystatechange = calShowUpload;
    http.send(null);
}
+4  A: 

You need two instances of the XMLHttpRequest or the second will stomp the first. The very, very easiest way to do this with your existing code is simply to create two instances and write your JS to use whichever one is appropriate to the task.

var http1 = getXHTTP(); // Use this for one request.
var http2 = getXHTTP(); // Use this for the other request.
Andrew
Just beat me to it :D
Josh Stuart
@josh - i was about to submit mine too
lock
Thank you very much
Wazzy
No problem. This is actually a really common problem. Another solution (if you end up with three or four -- or more -- instances of your xhr) is to build a queue mechanism. Instead of executing all your requests at once, throw them into a queue and execute the first in line. Then when the response from one request comes in, fire off the next request, and so on. If it gets much more complex than this, I'd say go with a library, such as jQuery, to abstract away all the complexity.
Andrew