Explain DOM 11 error in the initialization of XMLHttpRequest with JSON -headers

dom, javascript, json, xmlhttprequest

Solution

You need to `open()` the `XMLHttpRequest` before you can set request headers. Just move that line to after you call `open()`:

var xhr = new XMLHttpRequest();
xhr.open( 'POST', 'example.php', true );
xhr.setRequestHeader( 'Content-Type', 'application/json' );

Problem

I am getting this error as part of this larger puzzle here. ``` var xhr = new XMLHttpRequest(); xhr.setRequestHeader( 'Content-Type', 'application/json' ); //Error: INVALID_STATE_ERR: DOM Exception 11 ``` For further research O'Reilly's book "Definite Guide to Javascript 6th Edition" on page 491 in chapter 18 "Scripted HTTP" discussed XMLHttpRequest, please, note that it is not only about HTTP or XML (historical relics). Mozilla's dev entry about XMLHttpREquest here

Original source

Related problems