How do I test against readystate and status in a loop to avoid the else branch ?

603 views Asked by At

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.

1

There are 1 answers

0
Dexygen On BEST ANSWER

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!”);
        }
    }
};