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();
}
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();
}