I'm running a simple AJAX request:
function makePages(num) {
var conn = new XMLHttpRequest();
conn.onreadystatechange = function() {
if (conn.status === 200 && conn.readyState === 4) { //error here
$('#oldPost').before(conn.responseText);
}
else{
return
}
}
conn.open('GET','includes/feedExtra.php?num=' + num);
conn.send();
}
The code runs correctly and the PHP returns the correct content. However, there is an error in Chrome's console:
Uncaught Error: InvalidStateError: DOM Exception 11
it points to this line:
if (conn.status === 200 && conn.readyState === 4) {
What am I doing wrong?
The error:
Uncaught Error: InvalidStateError: DOM Exception 11
Means you are asking for status in the wrong state. conn.status is not available during readyState of 0 or 1.
Your problem is you are using conn.status when the readyState is 0 and 1.
You need to add code to make sure conn.status is not queried in the inappropriate states, like this:
if(conn.readyState === 4 && conn.status === 200){
Then your code will only query conn.status at the appropriate time.
Ref:
why does this piece of js throw a DOM Exception?
Try this:
conn.open('GET','includes/feedExtra.php?num=' + num, false);
false
makes the request synchronous, true
/ default is asynchronous.
In your case, it's defaulting to true
, which means the properties in your conditional (conn.status === 200 && conn.readyState === 4)
aren't available yet. They will be until after the call.
Hopefully that helps you some.
Also, checkout this discussion here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With