Ember Ember - 1 year ago 158
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>
var ajax;
if (window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
} else {
ajax = new ActiveXObject("Microsoft.XMLHTTP");

ajax.onreadystatechange = function() {
if (navigator.userAgent == 'code') {
ajax.open("POST", "location.txt", true);

location.txt contains the location of a file.


Instead of the
I inserted this:
. It did it three times, and only on the third did the window actually contain anything.

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

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

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download