Failed to read the ‘status’ property from ‘XMLHttpRequest’: the object’s state must not be OPENED

I try to detect rather the page status is 404 or not by this code :

var request = new XMLHttpRequest();  
    request.open('GET', 'http://xxxxxxxx.me/yossi/default.aspx', true);  
    request.send();  

    if (request.status === "404") {  
        alert("Oh no, it does not exist!");
    }  

and I get this strangiest error in my browser console :

Uncaught InvalidStateError: Failed to read the ‘status’ property from ‘XMLHttpRequest’: the object’s state must not be OPENED.

any clue whats going on ?

Answer

You’re opening the connection as ASYNC request.open('GET', 'http://*****/yossi/default.aspx', true); (the true part of the request).

This means that the request.send(); call is made and immediately continues execution of your program. While your program is continuing to process the next lines of code, the XMLHttpRequest is doing its own work in the background and making the HTTP request and thus the connection is currently in an “Open” state when the following code is hit:

if (request.status === "404") {  
  alert("Oh no, it does not exist!");
}  

You have two options

  1. Make the request.send(); call synchronous (vs async). This is NOT RECOMMENDED as the browser’s UI will freeze while the call is being made until your request returns.
  2. You need to add a callback for when the requests’ state has changed. This is done with an onreadystatechange property off of your request variable. Within the callback, you can check the status because it is not until the request has been completed that you would even be able to know if the status was “404” or not (or any other status for that matter). An example taken from http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp

Example of async call with onreadystatechange callback:

request.onreadystatechange = function() {
  if (request.readyState==4 && xmlhttp.status==404) {
    alert("Oh no, it does not exist!");
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *