tags:

views:

56

answers:

2

I'm learning Ajax at the moment. The code below basically receives the echo from the PHP and then puts it in element id games.

My question is, if I wanted to have Ajax send 3 different HTTP requests to 3 different PHP scripts and if I wanted to retrieve data from each one and then put it in 3 different element id's then would I make 3 copies of this same function? I would imagine that there should be a more efficient way.

function showHint(str) {
    if (window.XMLHttpRequest) {
        xmlhttp=new XMLHttpRequest();
    } else {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            document.getElementById("games").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","hw9.database.php?name="+str,true);
    xmlhttp.send();
}
+1  A: 

There is. Use a JavaScript framework like jQuery, Prototype or any other. All of them have built-in Ajax functionality that makes the things you want to accomplish a lot easier.

Example jQuery Ajax request:

$('#games').load('hw9.database.php?name=' + str );
Joop
This doesn't exactly answering my question, not to be rude.
Doug
Actually, he improved upon the solution to your answer.
RandyMorris
+5  A: 

There is no need to do that. You just have to parameterize the function:

function showHint(elementid,url,str) {

    if (window.XMLHttpRequest) {
        xmlhttp=new XMLHttpRequest();
    } else {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            document.getElementById(elementid).innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET",url+str,true);
    xmlhttp.send();
}
Pranay Rana
Ahh!! I see! This will work well!
Doug