Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

  1. 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).

  2. Mozilla's dev entry about XMLHttpREquest here

like image 606
hhh Avatar asked Jun 18 '12 13:06

hhh


People also ask

How do I fix synchronous XMLHttpRequest on the main thread is deprecated?

The solution to the above problem is to set async setting of the jQuery AJAX function to true as AJAX itself means Asynchronous JavaScript and XML and hence if you make it Synchronous by setting async setting to false, it will no longer be an AJAX call.

How do I fix unexpected end of JSON input?

You can solve the "Unexpected end of JSON input" error in the following 3 ways: wrap your parsing logic in a try/catch block. make sure to return a valid JSON response from your server. remove the parsing logic from your code if you are expecting an empty server response.

How do you check Ajax response is HTML or JSON?

The only reliable way to check if an arbitrary string is json or not in JS is to try and parse it, and catch the error. Also, the content-type won't tell you if it is valid json.

Why is synchronous XMLHttpRequest deprecated?

[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.


1 Answers

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' );
like image 140
Ry- Avatar answered Nov 13 '22 20:11

Ry-