2

I came across this post, which is pretty much what I'm looking to do:

How to extract url data from Reddit API using JSON

I have modified the jsfiddle that was provided (NSFW http://jsfiddle.net/DHKtW/170/) to read:

$.getJSON("http://www.reddit.com/r/pics/.json?jsonp=?", function(data) {
  $.each(data.data.children, function(i,item){
    console.log($('.score.likes').html(item));
  });
});

My goal is to gather the total amount of upvotes on a given page. When you run this and look at the console, objects are being returned but not the actual number. I thought just calling html on the selector would return the number of votes but apparently am wrong. Any better way of doing this?

Community
  • 1
  • 1
user3007294
  • 931
  • 1
  • 14
  • 33
  • 1
    When linking to adult content you should always inform people of this. I've edited your post to add **NSFW** (Not Safe For Work) before your JSFiddle link. – James Donnelly Oct 17 '14 at 13:15
  • What's `$('.score.likes')` for - is that the page you're working on? You're not attempting to parse the JSON using CSS selectors? – Rup Oct 17 '14 at 13:18
  • Thanks James. I was just re-using the post and didn't think about it that way...thanks for clarifying. Rup - $('.score.likes') is the selector of the DOM element where the actual votes value is housed. I read here http://stackoverflow.com/questions/10844664/on-reddit-how-do-scripts-get-the-number-of-upvotes-and-downvotes-for-a-comment that you can just grab it straight from the html... – user3007294 Oct 17 '14 at 13:23

1 Answers1

4

You need to console.log(item) to see the returned data. Using that we can then see that item.data.score returns the score of a post.

$.getJSON("http://www.reddit.com/r/pics/.json?jsonp=?", function (data) {
    $.each(data.data.children, function (i, item) {
        console.log(item.data);
        $('<div/>', {
            text: 'Post ' + item.data.permalink + ' has a score of ' + item.data.score
        }).appendTo('#images');
    });
});

http://jsfiddle.net/DHKtW/353/

The reason you saw objects without number is because you called console.log($('selector')) and that returns the jQuery object not the json from the request.

Spokey
  • 10,974
  • 2
  • 28
  • 44