7

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?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
bnynn
  • 501
  • 1
  • 6
  • 20

2 Answers2

14

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?

Community
  • 1
  • 1
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
2

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.

Community
  • 1
  • 1
couzzi
  • 6,316
  • 3
  • 24
  • 40
  • 1
    Wow thanks for the link I couldn't find anything like that, haha. It turns out that you were right, I needed to make sure that the 'readyState == 4' before I did anything so I just wrapped a huge if function around everything and the error is gone! :D – bnynn Mar 14 '13 at 00:04