why does this piece of js throw a DOM Exception?

javascript, xmlhttprequest

Solution

The problem is the status not available when the readyState is 0/1

You need to reverse the order in your if.

if(xhr.readyState === 4 && xhr.status === 200){

The spec says it should return zero "If the state is UNSENT or OPENED, return 0 and terminate these steps.", but for some reason some browsers do this "Throws an "InvalidStateError" exception if the state is not OPENED or if the send() flag is set." which is what setRequestHeader does. Also your code is weird that you would use it with a synchronous request.

So the issue here is the browser is not returning zero like the spec says so. Changing the order in the if statement prevents the browser from reaching that point since the first check fails.

And the bug on WebKit

Problem

I can't figure out why this fiddle throws Uncaught Error: InvalidStateError: DOM Exception 11 ``` function url(){ return '/echo/js/?js=' + 5 + Math.floor(Math.random()*900); } function poll(done){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.status === 200 && xhr.readyState === 4){ var foo = xhr.responseText; done(parseInt(foo)); } }; xhr.open('get',url(),false); xhr.send(null); } var button = document.querySelector('#poller'); var price = document.querySelector('#price'); button.addEventListener('click', function(){ poll(function(data){ price.innerText = data; }); },false); ```

Original source