/** Update time **/
function updateTime(){
var names = document.getElementsByName(\"time_elapsed\");
var total = names.length;
for(var i=0; i<total; i++){
var currentName = names.item(i);
var currentId = currentName.getAttribute(\"id\");
loadXMLDoc(\"GET\",\"update.php?id=\"+ currentId,function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
currentName.innerHTML= xmlhttp.responseText;
}
});
}
}
I wrote this code myself so I understand I'm probably missing something simple. But I've been error testing on it all day with no luck. For some reason the looped variables work fine outside loadXMLDoc(). But inside it only displays the last i value.
I found out that you have to use a synchronous XMLHTTPRequest. In this general XMLHTTPRequest function below if you set trueFalse to "false" (without the quotes) it will be a synchronous request.
ie: loadXMLDoc(\"GET\",false,\"example.php\", function(){ //code here });
Synchronous simply means that the code will halt until that specific request is finished and has returned a value. The problem I was having lied in the fact that the for loop itterated through faster then the XMLHTTPRequest could keep up, because it was not halting and waiting for a reply. The for loop pushed the last value to the function and therefore that is the only value that was changed.
Code:
/** General XMLHTTP Request **/
var xmlhttp;
function loadXMLDoc(GETPOST,trueFalse,url,cfunc){
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject(\"Microsoft.XMLHTTP\");
}
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open(GETPOST,url,trueFalse);
xmlhttp.send();
}
Bookmarks