Craig Lafferty
Craig Lafferty

Reputation: 791

Can't access Json value

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);
}

Upvotes: 1

Views: 7134

Answers (1)

m59
m59

Reputation: 43755

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).

Upvotes: 10

Related Questions