I have a little script in a html page that loops through an array, it runs an ajax function to check if a file is there, if it is..it prints a number off the array; if not it prints 0. The problem is that it just hangs (browser just sits there loading forever) after the first iteration. Is there a way to close the connection? I'm rather new to Ajax, so thanks for the help.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var cnt = 0;
var getNum;
var num = [25, 15, 24, 16, 23, 17, 22, 18, 21, 19, 20];
var response = 1;
function getAjax(sales, cnt, getNum){
loadDoc(response);
if(response == 1 )
{
if(cnt >= 11)
{
cnt = 0;
}
else
{
cnt++;
}
getNum = num[cnt];
}
else{
getNum = 0;
}
document.write(getNum + '<br/>');
}
function loadDoc(response)
{
var xmlhttp;
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=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
response = 1;
}
else
{
response = 0;
}
}
xmlhttp.open("GET","randomFile.js",true);
xmlhttp.send();
}
function runIt(num, cnt, getNum, response){
setTimeout('getAjax(num, cnt, getNum)', 3000);
}
</script>
</head>
<body>
<div id="alert"></div>
<button type="button" onclick="runIt(num, cnt, getNum, response)">Change Content</button>
</body>
</html>
XMLHttpRequests are asynchronous. This means everything here
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
response = 1;
}
else
{
response = 0;
}
}
is run a period of time after the request is made. More specifically:
...
loadDoc(response);
// the XMLHttpRequest might not have finished within this gap
if(response == 1 ) // <----- response might have not been updated yet
...
Therefore, if you immediately check the response
, it might not have been updated yet. Instead, everything that needs to be run that depends on the response should be placed in the callback function shown above. This includes your counter incrementing logic.
Additionally, you passed the response
variable into loadDoc
, which serves no purpose since response
is a global variable already.