Asker Asker - 28 days ago 10
Ajax Question

Ajax request -> request.readyState empty

I want to make a JS Ajax request but it doesn't work.
I wrote this code:

var i=0;
function send()
{
var request = new XMLHttpRequest();
request.open("GET", 'support.html', true);
request.send(null);
request.onreadystatechange = interpretRequest;
i++;
document.getElementById("debug").innerHTML=document.getElementById("debug").innerHTML+i;


}

function interpretRequest() {
document.getElementById("answer").innerHTML=document.getElementById("answer").innerHTML+"answer received";
document.getElementById("answer").innerHTML=document.getElementById("answer").innerHTML+request.status;
document.getElementById("answer").innerHTML=document.getElementById("answer").innerHTML+request.readyState;
switch (request.readyState) {
// if readyState == 4 and status == 200
case 4:
document.getElementById("Antwort").innerHTML=document.getElementById("Antwort").innerHTML+" answer received and state 4";

if (request.status != 200) {
alert("Error"+request.status);
} else {

var content = request.responseText;
// write content
document.getElementById("content").innerHTML = content;
}
break;
default:
break;
}
}


The function send is called by an intervall every s.I see that this works because
the nummers appears in the debug div. The function interpretRequest is called too. The string "answer received" appears but there is no print out which contains the request.status. In addition case 4 is never entered and the content div stays empty.

The HTML File is:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Test</title>

<script type="text/javascript" src="code.js"></script>
</head>
<body>
<div id="debug">Debug:</div>
<br /><hr />
<div id="content">HTML:</div>
<br /><hr />
<div id="answer">answer:</div>
</body>
</html>


The support.html is in the same folder and it contains:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h3>It works It works It works It works It workIt works</h3>
</body>
</html>

Answer

request isn't a global, so you can't access it from the interpretRequest function.

Use this instead.