2

Here is the json returned by an ajax call:

{
    "StumbleUpon": 0,
    "Reddit": 0,
    "Facebook": {
        "commentsbox_count": 0,
        "click_count": 0,
        "total_count": 0,
        "comment_count": 0,
        "like_count": 0,
        "share_count": 0
    },
    "Delicious": 0,
    "GooglePlusOne": 1,
    "Buzz": 0,
    "Twitter": 1,
    "Diggs": 0,
    "Pinterest": 0,
    "LinkedIn": 1
}

I'm trying to process it in jquery but for some reason that i fail to understand, Facebook.total_count is undefined. I would expect otherwise since the console tells me the above json was received. Moreover, all others (data.Twitter, etc.) work. Here is my callback function where the error is produced. What am i doing wrong?

function(data){

                console.log(data);
//this line throws the error
                var fb = data.Facebook;
                var total = parseInt(data.Twitter + parseInt(fb.total_count) + data.GooglePlusOne + data.Pinterest + data.LinkedIn);
// rest of code.
}

See the code on jsFiddle.

4
  • Create a pared down replicating test case. Your live link is way too much to expect people to wade through. The code you've quoted, for instance, isn't in any script blocks on that page, so which of the 15 included .js files should people be looking in? Commented Jul 24, 2012 at 12:54
  • But fb.total_count work? Commented Jul 24, 2012 at 12:56
  • @T.J.Crowder done, sorry for that. Commented Jul 24, 2012 at 13:07
  • @pixeline: Your fiddle doesn't give any error that I can see. Commented Jul 24, 2012 at 13:10

2 Answers 2

5

Fundamentally, that code works -- provided that data has already been deserialized. If it hasn't, either...

...add dataType: "JSON" to the ajax call:

$.ajax({
    // ...
    dataType: "JSON",
    // ...
});

...or use $.parseJSON on the result.

function(data) {
    if (typeof data === "string") {
        data = $.parseJSON(data);
    }
    // ...
}

Note: You don't need to use parseInt on those numbers, they're already numbers in the JSON and will be deserialized correctly.

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

1 Comment

Thanks, that was indeed the issue!
0

As far as I can see your receieving the JSON as a string but nor parsing it into an actual object. Theres too much on the page to really sift through and tell you accuratly but this seems to be the issue. try jQuery.parseJSON

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.