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);
}
Craig Lafferty
  • 771
  • 3
  • 10
  • 31

1 Answers1

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

m59
  • 43,214
  • 14
  • 119
  • 136
  • What's the difference between the string and the object? Also, I tried data.name and it was undefined. – Craig Lafferty Feb 02 '14 at 04:29
  • 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. – Craig Lafferty Feb 02 '14 at 04:34
  • @m59, you may want to mention jQuery.parseJSON - i was not aware that it is a standard feature in js 1.7. – i-- Feb 02 '14 at 04:45