Itslearning
Itslearning

Reputation: 47

Using AJAX, and retrieving the ready states

I am using the code behind for the retrieving the ready states and it's works good for me. May I please ask how can I add a else statemen in this content. Like if the url is not available I would like to print a message to user. Like

document.getElementById("div p").innerHTML = "Ping is not success!"; 

and try to make it looks like little bit more fancier then a plain html text. Her is the my code:

url = "<whatever you want to ping>"
ping = new XMLHttpRequest();    
ping.onreadystatechange = function(){

    document.body.innerHTML += "</br>" + ping.readyState;

    if(ping.readyState == 4){
        if(ping.status == 200){
            result = ping.getAllResponseHeaders();
            document.body.innerHTML += "</br>" + result + "</br>";
        }
    }

}
ping.open("GET", url, true);    
ping.send();

Upvotes: 0

Views: 235

Answers (1)

apsillers
apsillers

Reputation: 115950

When a requests ends, the readyState is 4, but the status may be a value other than 200. If the status is 0, that indicates a network error or CORS failure (for cross-origin servers). If it is some other value (like 404), that means the script reached the server, but the server didn't handle the request successfully (either because the URL path used wasn't meaningful, or a server-side error occurred, etc.)

ping.onreadystatechange = function(){

    document.body.innerHTML += "<br>" + ping.readyState;

    if(ping.readyState == 4){
        if(ping.status == 200){
            result = ping.getAllResponseHeaders();
            document.body.innerHTML += "<br>" + result + "<br>";
        } else if(ping.status == 0) {
            document.getElementById("foobar").innerHTML = "Ping is not successful! Could not get any response from the server, due to a network failure, CORS error, or offline server."; 
        } else {
            result = ping.getAllResponseHeaders();
            document.getElementById("foobar").innerHTML = "We got a response from the server, but it was status code " + ping.status;
        }
    }

}

Upvotes: 1

Related Questions