Jazib_Prince Jazib_Prince - 1 month ago 12
Ajax Question

Ajax Error: index.html:17 Uncaught InvalidStateError: Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED.sendAjax

On running index.html on local host using xampp it gives error:
index.html:17 Uncaught InvalidStateError: Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED.sendAjax @ index.html:17onclick @ index.html:28

Here is index.html file:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Show Ajax</title>

<script>
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.readyState === 4){
document.getElementById('ajax').innerHTML = xhr.responseText;
}
xhr.open('GET', 'data.html');

};
function sendAjax(){
xhr.send();
document.getElementById('load').style.display = "none";

}
</script>

</head>

<body>

<h1>Bring on ajax</h1>
<button id="load" onClick="sendAjax()">bring it</button>
<div id="ajax">

</div>

</body>
</html>


Here is data.html file:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
</head>

<body>
<p> Hello I'm Ajax, came here on your request</p>
</body>
</html>

Answer

You can't open the request inside the readyState handler, as that handler is only fired as the request is being made, after it's opened, you have to open the request before the readyState handler is called, but after it's defined, meaning outside the function, after it.

You should also generally create a new request object for each call to the sendAjax function, unless you have a very good reason not to do so

function sendAjax(){

    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {
        if(xhr.readyState === 4 && xhr.status === 200) {
            document.getElementById('ajax').innerHTML = xhr.responseText;   
        }
    };

    xhr.open('GET', 'data.html');
    xhr.send();

    document.getElementById('load').style.display = "none";
}
Comments