2levelsabove Posted August 29, 2008 Share Posted August 29, 2008 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 Quote Link to comment Share on other sites More sharing options...
Ken2k7 Posted August 29, 2008 Share Posted August 29, 2008 The purpose of the .readystatechange function is because you don't know when the AJAX information is available. If you put an alert statement outside that function, chances are, the AJAX data hasn't loaded. Quote Link to comment Share on other sites More sharing options...
haku Posted August 29, 2008 Share Posted August 29, 2008 That's exactly it. On a side note: req.send(null); If you are not actually sending any post data (which you aren't, since you are sending NULL), then it's better to make your AJAX call a 'get' call instead of a 'post' call. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.