Search code examples
javascriptajaxxmlhttprequestecmascript-5

How to handle when XMLHttpRequest fails?


I am trying to make an XHR call but if server is not online or if Internet is disconnected after the call is initiated then i get failed as status Network Log Screenshot

I tried onload(), onerror(), onreadystatechange() events but none of them are fired. Here is my Javascript snippet

function login() {
    animateLogo(true);
    document.getElementsByTagName('fieldset')[0].setAttribute('disabled', 'true');
    var http = new XMLHttpRequest();
    var url = "localhost:3000/login";
    var params = `email=${email}&password=${password}&remember=${remember}`;
    http.open('POST', url, true);
    http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    http.onload = function () {
        animateLogo(false);
        // Response handler
    }
    http.send(params); }

Since none of the events are fired i am unable to stop my animation


Solution

  • you can check for the status of the request (success = 200, notFound = 404, serverError = 500 etc..)

    const http = new XMLHttpRequest();
    const url = "localhost:3000/login";
    http.open('POST', url, true);
    const params = `email=${email}&password=${password}&remember=${remember}`;
    http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    
    http.onreadystatechange = function() {//Call a function when the state changes.
        if(this.readyState == XMLHttpRequest.DONE && this.status == 200) {
            // Request finished. Do processing here.
        }
        // handle other status here
    }
    http.send(params);