Max
Max

Reputation: 1459

JQuery AJAX trying to parse XML even with "dataType" : "JSON"

As the title suggests, I have the following:

$.ajax({
  "url" : ...
, "type" : "GET"
, "dataType" : "JSON"
, "success" : function(response_data) {
    that.data = response_data;
    success(response_data);
  }
, "onerror" : function(data) {
    console.log(JSON.stringify(data));
  }
});

But when I run it, I get

XML Parsing Error: syntax error Location: moz-nullprincipal

Looking at firebug, I see that the request was

Accept  application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-us,en;q=0.5
Cache-Control   max-age=0
Connection  keep-alive
Host    localhost:8888
Referer http://localhost:8888/
User-Agent  Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:13.0) Gecko/20100101       Firefox/13.0.1
X-Requested-With    XMLHttpRequest

Any ideas?

Upvotes: 0

Views: 4515

Answers (3)

Jeff Hoye
Jeff Hoye

Reputation: 590

The real problem is that your server is not setting the 'Content-type' header. Set it to 'application/json'.

For example in node.js:

res.setHeader('Content-type', 'application/json');

Upvotes: 1

Max
Max

Reputation: 1459

Ok great thanks to everyone tried to answer this.

But it turns out, as usual, I noob'ed out here.

The XML parsing error shown in firebug is not actually an error with the code, and firebug's failed attempt to guess it's XML and parse it.

My problem was elsewhere in the program and it was solved.

Upper vs lower case "JSON" did not make a difference.

Max

Upvotes: 2

greg84
greg84

Reputation: 7599

Change "JSON" to lowercase "json" first. But this is the type that jQuery is expecting back from the server, it's not necessarily what the server will send.

Are you sure that the server is returning JSON? Worth a double-check. Have you looked at the response in Fiddler? If it's XML it's the server's issue, not the script's.

Upvotes: 3

Related Questions