1

I am trying to access the json object passed into the loggedIn function.

{"name":"craig lafferty","ID":"1"} is output to the console but the result of console.log(data["name"]); is undefined. What am I missing here?

function loggedIn(data)
{
    console.log(data);
    console.log(data["name"]);
    $("#usernameDisplay").css({"z-index":"5"});
    $("#searchResultsContainer").css({"z-index":"3"});
    $("#usernameDisplay").text(data["name"]);
    $("#loginAddUserBack,#loginFacebook,#loginGoogle").animate({opacity: "0"}).delay(2, function(){$(this).css({"display": "none","z-index":"0"});});
    $("#menuIndic").css({"opacity":"0.3","z-index":"5"});
    $("#intro").animate({opacity: "0"}).delay(2, function(){$(this).css("display", "none");});
    $("#mainNotificationTable,#searchResultsContainer,#searchMainContainer").css("visibility", "visible");
    $("#searchTypes").css({"visibility": "visible", "z-index":"5"});
    id = data["ID"];
    //getUserInfo(username);
}

1 Answer 1

10

Your json is a string, not an actual object. Turn it into an object using data = JSON.parse(data) then it will work.

data = JSON.parse(data);
console.log(data["name"]);

Also note that you could just do data.name which is generally considered a little nicer unless you need something that bracket syntax offers (like a property name with a bad character or access property with a variable).

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

3 Comments

What's the difference between the string and the object? Also, I tried data.name and it was undefined.
Nevermind, I got it. I guess I was under the impression that the string with the bracket notation was parsed as an object from the literal string values.
@m59, you may want to mention jQuery.parseJSON - i was not aware that it is a standard feature in js 1.7.

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.