alnafie
alnafie

Reputation: 10798

XMLHttpRequest responseType = "json" giving error SYNTAX_ERR: DOM Exception 12

I am having trouble setting the XHR responseType to "json". It works fine if I leave it an empty string xml.responseType = ""; but when I set it to "json" I get the console error message SYNTAX_ERR: DOM Exception 12.

The .js file:

var xml = new XMLHttpRequest();
xml.open("GET", "test.php", true);
xml.responseType = "json";
xml.send();

The .php file:

<?php
$foo = "{\"key1\":\"val1\", \"key2\":\"val2\"}";
echo $foo;
?>

Not sure what's going on.. Any ideas?

Upvotes: 23

Views: 66515

Answers (2)

Peter Aron Zentai
Peter Aron Zentai

Reputation: 11740

The JSON responseType is not implemented in the WebKit. http://groups.google.com/a/chromium.org/group/chromium-bugs/browse_thread/thread/8107e50e4207eb5a/a5d2c31247feae56?lnk=raot

Update 2016-01-03: As could be expected, WebKit has implemented this feature in the meantime.

Upvotes: 8

Saket Patel
Saket Patel

Reputation: 6683

responseType property for XMLHttpRequest object is added in its new variant XMLHttpRequest Level 2 and which is included in HTML 5, i am not sure all browsers support this method so it could be possible that you are using a browser which doesn't implement that method

instead of using responseType you can use following code to get data in desired format

 var xml = new XMLHttpRequest();
 xml.open("GET", "test.php", true);

 xml.onreadystatechange = function() {
   if (xml.readyState != 4)  { return; }

   var serverResponse = JSON.parse(xml.responseText);
 };

 xml.send(null);

Upvotes: 32

Related Questions