Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught Error: InvalidStateError: DOM Exception 11 with AJAX?

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?

like image 776
bnynn Avatar asked Mar 13 '13 23:03

bnynn


2 Answers

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?

like image 68
Eric Leschinski Avatar answered Nov 13 '22 10:11

Eric Leschinski


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.

like image 2
couzzi Avatar answered Nov 13 '22 09:11

couzzi