I have three div elements, and I want to populate each element with its own content. I call the same AJAX (very generic) function each time, sending the name of the div id as a parameter:
//left-right rectangle content
var rl = getContent("rightLeft");
//bottom content
var br = getContent("bottomRectangle");
//top content
var rtr = getContent("rightTopRectangle");
If I do an alert(http.responseText) within the AJAX function, I get the correct html content from the remote page. (In fact, if I add an alert, it seems to “slow” the function down so that my content is returned properly each time I call it, but who wants alerts on their web page?).
But, without the alerts, the above calls will only properly process the last call. So, in the above sequence of calls, only the last div, where id=”rightTopRectangle” will be filled with the html retrieved from the AJAX call. The previous two calls don’t populate their divs with the AJAX retrieved html. If I shake up the order of the calls, it will always be the last AJAX call that works.
I get the feeling the problem has something to do with the asynchronous part, where the previous calls don’t have enough time to process the request before the AJAX function is requested again and again.
Here’s the AJAX function:
function getContent(element){
var url = "ajax/getcontent.php?cid="+element; //alert(url);
http.onreadystatechange=function(){
if (http.readyState==4 && http.status==200){ //alert(http.responseText);
var response = http.responseXML.documentElement;
callback(element,http.responseText);
}
}
http.open("GET",url,true);
http.send();
}
The function named “callback” (it works fine) looks like this:
function callback(e,c){
document.getElementById(e).innerHTML = "<div style=\"line-height:"+ document.getElementById(e).offsetHeight +"px;margin:0px auto 0px auto;text-align:center;\" >" + unescape(c) + "</div>";
}
UPDATE: This works now. I added one line to my getContent function:
function getContent(element){
var http = createRequestObject(); /*After Tej's answer, I took this line out
of the root of my script and placed it here, within the function, in order to
instantiate a new http object each time I call this function, so that they all
operate independently of one another*/
var url = "ajax/getcontent.php?cid="+element; //alert(url);
http.onreadystatechange=function(){
if (http.readyState==4 && http.status==200){
var response = http.responseXML.documentElement;
callback(element,http.responseText);
}
}
http.open("GET",url,true);
http.send();
}
You are re-using the same
XmlHttpRequestfor all of your ajax requests; this leads to the last request always winning because the others have been overwritten. You should instead create a new ajax request for each call.