2

I'm trying to develop a web application using jQuery, AJAX and JSON. I have this code:

console.log(response.s);
if (response.s == true) {
    alert('good');
} else {
    alert('bad');
}

This response (via console.log() on Firebug) seems to be:

{"s":true}

Which seems to be a JSON object right? Well, the line console.log(response.s); on the first code I added here returns undefined. What's the problem?

2
  • Can you click the {"s":true} object within Firebug console and see it in object (DOM) explorer or is it written as string in the Firebug console (i.e. not clickable)? Commented Mar 18, 2011 at 15:09
  • @Nikhil, i guess it more like a string. Commented Mar 18, 2011 at 15:10

3 Answers 3

8

What is typeof (response)? if it's a string then you have to parse it, first. (You'd be accessing the s field of a string, which doesn't exist, so JavaScript gives you undefined instead of throwing an Exception or whatever.)

Sign up to request clarification or add additional context in comments.

4 Comments

How can i check the type of it? How could i parse it?
literally type in typeof (response.s) in the console. or type in response.s.constructor and see what that gives you.
I think you meant to ask about typeof response. If that returns "string", OP needs to call jQuery.parseJSON( response )
Yes it was a string. I just added dataType: 'json' to my ajax jQuery request and it worked fine. Thanks.
1

If the content-type of the response isn't application/json then the javascript is probably assuming that it is just a string.

Supplying the correct content header should therefore sort your problem.

Alternatively you could probably use eval() to convert the string into a json object.

Comments

1

try to use:

var obj = jQuery.parseJSON(response);
console.log(obj.s);

Hope it helps.

Comments

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.