Click to See Complete Forum and Search --> : Why am I getting weird results in my Ajax call ? Im so frustrated!!!


2levelsabove
08-28-2008, 09:38 PM
The function below has 2 alert boxes. When I run it, sometimes the outer alert box comes empty. Please explain in a human manner why



function ItemCount()//returns the number of items in carousel
{


if (window.XMLHttpRequest) {
var req = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
var req = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("upgrade browser");

}


req.open("POST", "/includes/_process/getPortfolioCount.php", true);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.send(null);
req.onreadystatechange = function() {
if ((req.readyState == 4) && (req.status == 200)) {


if (req.responseText.length) {


document.getElementById('portfolioCount').value=req.responseText;

alert(req.responseText);

}

}
}

alert("out:"+document.getElementById('portfolioCount').value);




return document.getElementById('portfolioCount').value;

}//function

jazz_snob
08-29-2008, 02:47 AM
OK, I'm gonna make a guess that its becuase AJAX is asynchronous, meaning sometimes the "outer" alert, meaning the one starting with "out:" in it, executes before the AJAX request finishes.