1

i have this code which is using an asynchronous AJAX object , xmlhttp

xmlhttp.open(’GET’, url, true);
xmlhttp.onreadystatechange = function ()
{

    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        alert(xmlHttp.responseText);
    }
    else
    {
        alert(”Error: Failed request!”);
    }
};
xmlHttp.send(null); 

I know that my problem is that the if condition fails until the readystate reaches 4 resulting in me clicking away an alert box 3 times,

I think that the answer is to test against readystate and status in a loop to avoid this but i am unsure how to write the correct loop.

Aaron
  • 75
  • 8
  • 1
    `onreadystatechange` is called when the ready state changes. No loop needed, just remove the `else` branch. If you want to show an error if the status is not `200`, create a nested `if` statement. – Felix Kling Dec 16 '14 at 20:44

1 Answers1

3

As noted in the comment, no loop is needed. What is needed is a better understanding of the readystate values that come before 4: they do not connote failure -- see https://stackoverflow.com/a/632800/34806 and particularly "In practice you almost never use any of them except for 4".

What probably connotes failure is not getting back xmlhttp.status == 200 ("In most cases, you can assume anything other than 200 is an error situation." -- see http://ajaxpatterns.org/XMLHttpRequest_Call#Detecting_Errors). Bearing all this in mind your code could be re-written as follows:

xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState==4) {
        if (xmlhttp.status==200) {
            alert(xmlHttp.responseText);
        }
        else {
            alert(”Error: Failed request!”);
        }
    }
};
Community
  • 1
  • 1
Dexygen
  • 11,681
  • 11
  • 73
  • 144