5

I am experiencing a strange problem while trying to parse JSON strings in jQuery AJAX response. Here is my code:

$.ajax({
    type: "POST",
    url: "Save",
    data: {
        expiry: expiry,
        settings: settings
    }
}).done(function (msg) {
    alert(msg);
    var obj = jQuery.parseJSON(msg);
    if (obj.status == "done") {
        window.location = obj.redirect;
    }
});

On IE, Chrome, and Safari, I am getting JSON string in alert, but on Firefox, I am getting

[obj XMLDocument]

in the alert.

Here is FF console:

enter image description here

obj is null, but I can see the response JSON string in the console under text attribute

responses=Object { xml=document, text="{"status":"done","redir...ippetImage\/s\/6abb68"}

Any reason for this behavior?

2 Answers 2

5

Problem was on servlet side. I had to set contentType to make it work.

response.setContentType("text/JSON");
Sign up to request clarification or add additional context in comments.

Comments

1

That's not a valid JSON string. A JSON string is, for all intents and purposes, simply the right-hand side of an assignment in JS.

e.g.

var x = 7;
        ^
var y = [1,2,3];
        ^^^^^^^
var z = {a:'b', c: 'd'};
        ^^^^^^^^^^^^^^^

The parts indicated by ^ correspond to what you'd get if you converted the x/y/z vars to JSON strings.

If you can't write your json string as a JS assignment, e.g.

var x = ...json_string_here...;

then it's not valid JSON. Your snippet boils down to:

var x = responses=Object { .... }

which is a syntax error.

3 Comments

Coincidence probably. The fact that it works on other browsers doesn mean it's proper JSoN.
{"status":"done","redirect":"some_url"} is their any problem with this json string ?
response=Object {...} is Firebug's way of printing an object. You have misapprehended the question (and also the JSON spec: {a:'b', c: 'd'} is not valid JSON, {"a":"b", "c": "d"} is)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.