Pipeline
Pipeline

Reputation: 1059

Reddit API - difference between API and appending .json and getting front page info

I am newcomer with making applications dealing with other API's, especially ones that require OAuth authentication.

For now, I am trying to simply fetch information about the front page listing of Reddit in my application.

I am looking at this Reddit API doc here, but then I am reading that to get a JSON representation of Reddit you just have to add a .json after the url.

So I am sending a HTTP GET request like:

$(document).ready(function () {

    httpGetAsync("https://www.reddit.com/.json");

});

function httpGetAsync(url) {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            alert(JSON.stringify(xmlHttp.responseText, null, 4));
    }
    xmlHttp.open("GET", url, true); // true for asynchronous 
    xmlHttp.send(null);
}

But this seems to be only returning what seems is the LAST post on the reddit page or maybe I cannot tell since the alert box cannot show the enormous JSON response?

I figured this was the case and tried:

var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
        parseResponse(xmlHttp.responseText);
}
xmlHttp.open("GET", url, true); // true for asynchronous 
xmlHttp.send(null);


function parseResponse(responseText) {
var x = (JSON.parse(responseText));
alert(x.count);

}

but got a undefined in the alert box. Any ideas?

Goal is to get the 25 front page of reddit JSON responses information (identifiers)

Upvotes: 1

Views: 458

Answers (2)

Fraser Crosbie
Fraser Crosbie

Reputation: 1762

You might want to use jQuery to retrieve and parse the data:

$.getJSON( "https://www.reddit.com/.json", function( data ) {
  $.each( data.data.children, function( i, obj ) {
     console.log(obj.data.id);
  });
});

I made a working example for you that retrieves the first 25 IDs:

https://jsfiddle.net/enmpw8qf/

Upvotes: 1

Alex Allen
Alex Allen

Reputation: 76

Try using console.log(...) instead of alert(...) for displaying information. Open the console (F12 on Chrome) and view the output there.

JSON.stringify(xmlHttp.responseText, null, 4)

xmlHttp.responseText is already a string; you're trying to stringify a string.

Instead try (if you just want to see the text):

console.log(xmlHttp.responseText);

Or if you want to see the object:

console.log(JSON.parse(xmlHttp.responseText));

Upvotes: 1

Related Questions