Ember Ember - 3 months ago 14
Ajax Question

ajax to location.replace(ajax.responseText) reloads forever

I can't figure out why this is happening, and there is no documentation of it:

<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<h1>HideSite</h1>
<script>
var ajax;
if (window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
} else {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}

ajax.onreadystatechange = function() {
location.replace(ajax.responseText);
}
if (navigator.userAgent == 'code') {
ajax.open("POST", "location.txt", true);
ajax.send();
}
</script>
</body>
</html>


location.txt contains the location of a file.

Update:



Instead of the
replace()
I inserted this:
alert(ajax.responseText)
. It did it three times, and only on the third did the window actually contain anything.

if (ajax.responseText != undefined && ajax.responseText != "") {
alert(ajax.responseText);
}


When I added this it only did it twice, both times containing the correct string

Answer

The onreadystatechange event gets hit multiple times during the life of an AJAX call; a majority of these hits will not actually be delivering any response text. The ready states are as follows:

0: request not initialized 
1: server connection established
2: request received 
3: processing request 
4: request finished and response is ready

Being as you've said "on every state change" rather than "when the response is ready", more often than not your AJAX call has not yet received the response. I would suggest modifying your event to include an if statement like so:

ajax.onreadystatechange = function() {
   if (ajax.readyState == 4) {   //WHEN RESPONSE IS READY
      location.replace(ajax.responseText);
   }
}
Comments