Why XmlHttpRequest readyState = 2 on 200 HTTP response code

snowbound picture snowbound · Oct 17, 2014 · Viewed 19.6k times · Source

So I'm using plain javascript (no jquery), to send a file to the server. Server script PHP returns status code 200 at the end, but instead javascript is getting readyState == 2.

The PHP code sends back status code 200:

header('X-PHP-Response-Code: 200', true, 200);
exit;

The javascript is doing:

request.onreadystatechange = function() {
        if (request.readyState == 4) {
            var message;
            switch(request.status) {
                case '200':
                     message = "Data uploaded successfully.";
                break;

                case '406':
                    message = "Incorrect file format.  Please try again.";
                break;

                case '410':
                    message = "Unexpected error.  Please contact support.";
                break;

                default:
                break;
            }
            status_message_container.innerHTML = message;
            submit_button.disabled = false;
        }
        else {
            alert( "Unexpected error:  " + this.statusText + ".\nPlease try again");
        }
    };

    request.send(formData);

Even know the HTTP 200 status code comes back correctly (I get 'OK') on frontend. The JS script is seeing readyState==2 (i.e. else block always hit)

My understanding is that a server status code of 200 should give readyState == 4??

Answer

CodingIntrigue picture CodingIntrigue · Oct 17, 2014

Firstly, onreadystate isn't just fired once. It's fired multiple times, you need to be able to handle that. These are the codes you need to handle:

0 UNSENT - open()has not been called yet
1 OPENED - send()has not been called yet
2 HEADERS_RECEIVED - send() has been called, and headers and status are available
3 LOADING Downloading; - responseText holds partial data
4 - The operation is complete

Your code is hitting the else block on readyState == 2 (headers received) and assuming that is an error status when it's not.

You error check should be inside the request.readyState == 4 check. That way, the request is complete but there could also have been an error:

if (request.readyState == 4) {
    switch(request.status) {
        case '200':
            message = "Data uploaded successfully.";
        break;
        // Error handling here
        default: alert( "Unexpected error:  " + this.statusText + ".\nPlease try again"); break;
    }
}

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest