1

I would like to append my div with first permalink from subreddit. I've tried following jQuery's documentation, Smashing Magazine's article and reddit's github but without any effect. Please help me understand how to do this.

Jquery:

$(document).ready(function(){
        $.getJSON("api.reddit.com/r/aww/.json", function(json){
           $(".slodziaki").append("<p>Permalink</p>"+ json.data.children.data[0].permalink)'         
        });
});

HTML:

<html>
    <head>
        <meta charset="utf-8">
        <title>Słodziaki.</title>
        <script>

        </script>
    </head>
    <body>
        <div class="slodziaki">
            Reddit api test.
        </div>
    </body>
</html>

jsFiddle: http://jsfiddle.net/AdVS3/2/

metrampaz
  • 663
  • 1
  • 6
  • 12
  • Duplicate of http://stackoverflow.com/questions/8191105/how-to-extract-url-data-from-reddit-api-using-json – Niko Mar 10 '12 at 17:46
  • `api.reddit.com/r/aww/.json` is not a proper URL but just a URL path. – Gumbo Mar 11 '12 at 10:16

1 Answers1

2

You've got the right idea, but most browsers won't allow you to access api.reddit.com because of XSS protection and the Same Origin Policy. Another option is to use cURL or similar via your server side script to pull in the JSON, and jQuery would access that resource from the local server. If you provide your scripting language, I can help even further.

Luckily, this is pretty easy with PHP. You've got quite a few options, but I'd suggest starting with file_get_contents() from that page. If you're looking for a performance increase, you should explore the cURL options also noted there. Fairly straight forward, all it does is go out to the specified URL (api.reddit.com/r/aww/.json) and displays it locally.

If you were to put that into a file called aww.php, then you would just call aww.php in your .getJSON function.

Nic
  • 13,287
  • 7
  • 40
  • 42
  • Thank you very much for your reply. It is quite interesting because previously I thought I just could use anything I can access to (just like an iframe) but you've proven me wrong what I am thankful for. Unfortunately I am a front-end guy and I have no knowledge of server-side languages. However I want to accomplish my project so bad that I am eager to learn some basics of a scripting language, my current webserver provides only PHP (didn't plan to learn it) so that's what I am going to stick with now. Please provide me with techniques on how to do it. Thanks in advance. – metrampaz Mar 10 '12 at 17:53
  • you can use Yahoo YQL as a proxy to get the data, only take you a few minutes to setup in their sandbox console – charlietfl Mar 10 '12 at 18:32
  • That a script can’t send a request to or read the response from a different domain does not have anything to do with XSS. – Gumbo Mar 11 '12 at 10:19
  • 1
    I've found another answer – JSONP is a cross-domain AJAX and it works everywhere. – metrampaz Mar 11 '12 at 11:55