0

I have the following message returned from a get:

{"status":"success"}

my code looks like this:

$.get(url, function(result) { 
        console.log(result)                  
        console.log(result['status'])
            console.log(result.status)          
        return false;
    });

This prints the following:

{"status":"success"}
undefined
undefined

What am I doing wrong?

4 Answers 4

1

If your console.log is showing "{"status":"success"}", that means your JSON wasn't parsed. You need to tell jQuery to do that for you:

$.get(url, function(result) { 
    console.log(result);     
    console.log(result['status']);
    console.log(result.status);
}, 'json');

Or, better yet:

$.getJSON(url, function(result) { 
    console.log(result);     
    console.log(result['status']);
    console.log(result.status);
});
Sign up to request clarification or add additional context in comments.

Comments

1

You must specify that you're expecting to receive JSON data. It is yet another parameter in the jQuery.get function

$.get(url, function(result) { 
    console.log(result)                  
    console.log(result['status'])
        console.log(result.status)          
    return false;
}, 'json'); // <---- HERE

Without that, your result is treated as a string.

Comments

0

Your JSON is probably not served with a proper HTTP header identifying it as JSON (you can check the header in the "network" tab of the development tools of your browser), it's probably not parsed. Try

console.log(JSON.parse(result)['status'])

or set the datatype to "json".

If you manage the server, you should fix the header.

Comments

0

Presumably: You are serving the JSON with the wrong Content-Type header so jQuery is not passing it through a JSON parser.

Make sure the URL returns Content-Type: application/json in the headers.

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.