Estimated reading time: 2 minutes, 56 seconds

How to make a Facebook feed using the Graph API, JSON and jQuery

Hey all,
After scouring the internet for a tutorial I took it on myself (after realising there was none) to teach the world how to use the new cool Facebook graph api with JSON along side with jQuery to make a cool feed for use on websites.

From this you can do anything and even do a live feed using ajax. Maybe i’ll do a tutorial on that sometime soon.

UPDATE: Facebook have recently changed their api and policy. To access a feed now requires an access token. We will create a new tutorial soon. P.S. Please don’t copy the code in the source on our working feed, this will expire and is insecure to use on your own website, thanks.

Follow @PrettyKlicks for more news and tips.

CRITICAL NOTICE: There was a security vulnerability kindly pointed out by Rick, this can be fixed very easily. Please update your code. See below!

Check out our demo here: DEMO

So first things first. You need to set up your page for jQuery by adding the lines:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
You need to place this into the tags.

The URL

Now we need to identify where our json results are coming from facebook and the url for it so we can fetch the data.

This is our url for Pretty Klicks:

http://graph.facebook.com/prettyklicks/feed

Notice the /feed this is because we need to tell facebook not only is it the username prettyklicks but also we want to get the results for the feed. We’re not done yet. We need to add some extra things to the url.

http://graph.facebook.com/prettyklicks/feed?limit=5&callback=?

First of all we called the limit parameter to tell facebook we only want the 5 latest wall posts and more importantly we added callback=? This is because JSON is not meant to work cross domain. Therefore so we can work around this and to help jQuery set the callback itself and then process our JSONP we add the ‘?’ to let jQuery do it for us.

Parsing the JSON result with our jQuery function

Right so now we need to create our javascript to parse the json results. I have commented the code to show you what each bit does.

function fbFetch(){
//Set Url of JSON data from the facebook graph api. make sure callback is set with a '?' to overcome the cross domain problems with JSON
var url = "http://graph.facebook.com/prettyklicks/feed?limit=5&callback=?";

//Use jQuery getJSON method to fetch the data from the url and then create our unordered list with the relevant data.
$.getJSON(url,function(json){
var html = "<ul>";

//loop through and within data array's retrieve the message variable.
//XSS ATTACK FIX AS OF 6/1/12 PLEASE UPDATE TO THIS ASAP.
$.each(json.data,function(i,fb){
html += "<li>" + $('<div>').html(fb.message).text() + "</li>";
});

html += "</ul>";

//A little animation once fetched
$('.facebookfeed').animate({opacity:0}, 500, function(){
$('.facebookfeed').html(html);
});
$('.facebookfeed').animate({opacity:1}, 500);
});
};

(I just broke it into 3 sections to make it easier to read)

Now we have our function set in thewe need to set out our html and initiate the function onload. Our html should look something like this at the very least.

<body onLoad="fbFetch()">
<div class="facebookfeed">Loading...</div>

And thats a wrap! All we need to do now is style it out.

Check out our demo here: DEMO

And lastly please feel free to comment. Feel free to use this script. All we ask is you follow us on twitter @PrettyKlicks and maybe give us a some credit for it via a link back :)

….Some shameless seo:
Deeside Web Design

Posted in Tips & Tricks | Tags: , , , | 63 Comments
By |

60 Comments

  • pluppfisk

    Thank you!
    Just what I was looking for!
    Since I don’t have access to the body tag on the publishing system I use I put the onload event on an image on the page instead and that worked just fine too. :)

    Posted September 6, 2010 at 3:02 pm | Permalink
  • Darren

    Marvellous coding! Thanks, jus the kinda thing i’ve been looking to do. Would be interested to see an ajax live feed :)

    Posted September 9, 2010 at 10:33 am | Permalink
  • Jason

    awesome. i did change one thing tho.

    if (fb.message) {
    html += "" + fb.message + "";
    }

    that way you wont get an ‘undefined’ from certain wall posts

    Posted September 21, 2010 at 9:01 pm | Permalink
  • measles

    this is great!

    i’m going to try to use your code as a start off place to build a facebook photo album powered image gallery. thank you!

    Posted September 23, 2010 at 8:18 pm | Permalink
  • avinash

    Thanks a lot it helped me a lot

    Posted October 4, 2010 at 4:46 pm | Permalink
  • Awesome, thanks for sharing, you just saved me a couple hours of wondering why i was returning nulls from my getJSON requests!

    Posted October 13, 2010 at 6:17 pm | Permalink
  • andres

    Man, you save my life!!!!!

    Posted October 21, 2010 at 3:39 am | Permalink
  • Benji

    Hey there, awesome example. Have made it into a plugin which is now in the Jquery plugins repository, the source on github and an updated demo. Thanks for the inspiration.

    Posted November 3, 2010 at 1:11 am | Permalink
  • Stewart Simpson

    Hi,
    Excellent example of facebook wall integration.
    I was reading for hours before I found this and it’s way simpler than anything else I’ve found.
    Thanks
    Stewart

    Posted November 13, 2010 at 8:41 pm | Permalink
  • joe

    anyone have an idea on how to make the feed show one by one in a ticker style?

    Posted November 14, 2010 at 5:33 am | Permalink
  • Richard

    Very nice example… I too was struggling with using jQuery with the Facebook Graph API but this gave me exactly what I needed. Thanks for the great post!!

    Posted November 15, 2010 at 9:35 pm | Permalink
  • thanks a lot man !
    you save my time, my money and my life.

    Posted November 17, 2010 at 8:03 pm | Permalink
  • Chris

    Great example.

    You can also pull fb.created_time from the json output, but it would be nice to have it show the post’s age with a time difference between the current time and created time. Anyone have some suggestions?

    Posted November 18, 2010 at 1:00 am | Permalink
  • Thanks, this is just what I was looking for!

    If you want to restrict the feed to your own posts (i.e. exclude everyone else’s posts on your wall), you’ll want to replace “feed” with “posts” in the URL.

    Posted November 18, 2010 at 5:51 am | Permalink
  • I looked for days for something similar to no success.
    This has helped me out great, and just in time for my site live date. It will be live soon but here is the link.
    THANKS
    bRc
    here

    Posted November 24, 2010 at 11:16 pm | Permalink
  • Ryan Whinery

    Wanted to share what I had done with this code. Thank you very much for showing this. As you did, I was trying to come up with the exact same thing. You saved me an additional 2 days worth of work. I added in pictures and added in code to exclude undefined message and only show pictures for those post that hame them and avoid the red X

    var html = “”;
    //loop through and within data array’s retrieve the message variable.
    $.each(json.data,function(i,fb){
    if (fb.picture && fb.message)
    {
    html += “” + fb.created_time + “” + fb.message + “” + “” + “” ;
    }
    else

    if (fb.message)
    {
    html += “” + fb.created_time + “” + fb.message + “” + “” ;
    }}

    );
    html += “”;

    Posted December 3, 2010 at 10:26 pm | Permalink
  • I am trying to do the same to eci company page using the following url but nothing is being loaded
    “http://graph.facebook.com/ECITelecom/feed?limit=5&callback=?”
    heeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeelp!!!

    Posted December 9, 2010 at 12:21 pm | Permalink
  • When I started to read about integrating facebook into my own website I understood mostly everything… except how to get the data out of the JSON results and in to something meaningful! Thanks for this post, even though I haven’t tried it yet, I ahve a firm grasp on how to.

    Posted December 9, 2010 at 9:26 pm | Permalink
  • Melvin

    I tries using your code and it works well.

    but when I try to put it in an fbml page tab, Its now working,because fbml page tab is not allowing external scripts. Can I ask what must I do to put your code in an fbml page tab?

    Posted January 7, 2011 at 8:04 am | Permalink
  • I have a feeling you cannot do this, I may be wrong, I think it requires user input to activate certain javascript capabilities.

    Posted January 13, 2011 at 12:18 am | Permalink
  • Rui L

    Thank You for this script.
    Does anyone knows how to filter out posts that were not made by the page itself? I would like to use this on my website but it shows content that others write on my FB page.

    Thanks in advance

    Posted February 3, 2011 at 11:34 pm | Permalink
  • Rui L

    forget my last post ;) i just saw the solution that ben gave

    Posted February 3, 2011 at 11:38 pm | Permalink
  • Chris

    This (and the linked plugin) do not work in Chrome :( . They appear to function properly in ie8 and ff. I went through the debugger in chrome, but there are no errors being fired.

    When tested locally it works, but when uploaded to a server (including this test and the plugin test site) it just stays on the loading message.

    Using alerts to track the progress shows that Chrome thinks fb is undefined.

    Posted February 8, 2011 at 6:26 pm | Permalink
  • This is great! I’ve been trying to do this for two days now… and I wasn’t even close! Thanks so much!

    Posted February 25, 2011 at 2:45 pm | Permalink
  • Great post! One question: it creates an unordered list. Has anyone modified this to create a nested list so that page posts and comments on the page posts appear nested properly?

    Posted March 9, 2011 at 3:56 pm | Permalink
  • Thanks, just what I was looking for.

    Posted March 13, 2011 at 3:49 am | Permalink
  • Superb! Thank you:)

    Posted March 19, 2011 at 11:04 pm | Permalink
  • Ephobe

    how do you check succcess or failure of the feed?

    Posted March 24, 2011 at 8:09 pm | Permalink
  • Hi all, this is a great script! I really appreciate it. I have used it like this:

    if (fb.message) {
    if(fb.link){
    html += "" + fb.message + "";
    }else{
    html += "" + fb.message + "";
    }
    }

    I am trying now to have say 5 posts fade in and out, 1 at a time. Any thoughts? If I figure it out… I’ll send a comment. Thanks again!

    Posted March 26, 2011 at 8:59 pm | Permalink
  • Maarten Lauwaert

    Cool! But how do you use this code with a feed that needs an access token? Like a photo album?

    Greets!

    Posted March 28, 2011 at 4:04 pm | Permalink
  • Thanks for this code I’ve been looking for something like this for a while. The Facebook API Feed only seems to work if you have an active Facebook session on the browser. However I can’t seem to access any of my /feed or /posts data like I can certain other friends. I used my alias and Facebook ID but I get no data except for just the basic graph.facebook.com/MYID/ data. Is there a Facebook setting that I need disabled to access this data?

    Posted April 2, 2011 at 9:21 pm | Permalink
  • dhiraj

    is there anyway you can upload photos to album using jquery/ajax/graph api;

    i tried it using jquery but got error
    please help view the question at:
    http://stackoverflow.com/questions/5708328/uploading-photo-using-jquery-ajax-method-facebook-graph-api

    Posted April 19, 2011 at 12:23 pm | Permalink
  • Hey, thanks, great script. Do you have any ideas on how to page this?

    Posted May 31, 2011 at 1:38 am | Permalink
  • Dev

    When I click on your DEMO link – it says ‘Error on page” (tried using Firefox and IE8)
    Does that mean the whole is suspect, or just the demo?

    Posted June 4, 2011 at 8:47 pm | Permalink
  • Ben

    Unfortunately, it seems that recent changes to the Graph API, this doesn’t seem to work any more; it needs an access_token.

    Posted June 5, 2011 at 8:02 pm | Permalink
  • Ken

    I found this page and your code worked fantastically… till yesterday when it stopped working, I came back to your site and it appears your example has stopped working as well.

    It looks like Facebook has increased the amount of authentication required to access the feed from their graph. I’m going to have to find another way to fix this issue.

    Posted June 7, 2011 at 7:39 am | Permalink
  • Bob Larson

    Facebook just went around and is now requiring tokens to make this idea work. Just broke some stuff on a production site. Just a warning to everyone to go and make sure your stuff is still working. Most likely it is not and an throwing an OAuth exception

    Posted June 7, 2011 at 1:45 pm | Permalink
  • Timothy Aaron

    This no longer works (without warning). It now requires an OAuth 2.0 Authorization (even if it’s public).

    Very frustrating. Any solutions?

    Posted June 7, 2011 at 4:35 pm | Permalink
  • Just wanted to let you know, that Facebook (or maybe something else happened) changed access to JSON feed, so now it requires access token to get the JSON feed.

    Your script will give error “Uncaught TypeError: Cannot read property ‘length’ of undefined” because of ‘json.data’ will be UNDEFINED.

    JSON feed now contains:

    {
    “error”: {
    “type”: “OAuthException”,
    “message”: “An access token is required to request this resource.”
    }
    }

    Posted June 8, 2011 at 2:21 pm | Permalink
  • Hi Pretty Klicks,

    I loved this implementation and have been using it for some time, I recently found it broken so came back to see the source. I found your Demo is down and throwing the same issue I experienced.

    I found my solution – http://itslennysfault.com/get-facebook-access-token-for-graph-api

    Seems Facebook requires an accesskey now due to it’s switch to OAuth 2.0

    Figured you’d appreciate the heads up so you can fix your implementation.

    Posted June 9, 2011 at 10:34 pm | Permalink

3 Trackbacks

  1. By Our first Jquery plugin of many on November 3, 2010 at 1:36 am

    [...] does this called Tweet there isn’t anything for Facebook. Inspired by the code written by Pretty Klicks we wrote a simple little plugin called fbStatus. Plans in the next revision will be to more of the [...]

  2. By How to read Facebook Graph API feed using JQuery on March 22, 2011 at 2:56 am

    [...] hopefully this code was helpful in your Facebook development. Special thanks to PrettyKlicks for the inspiration to write this. Enjoy! Share and [...]

  3. [...] Append your Facebook Graph url (example link from PrettyKlicks JSON Facebook [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribe
Keep up to date with our latest posts.

Learn more about making the most of your website, marketing and seo. It takes two seconds to subscribe to our rss feed.
Contact
You can get in contact with us via phone or e-mail, we will get back to you very promptly.

0141 416 2221
Call you back?
If you would like us to call you back, just pop your number in below and we will get back to you very soon!

Copyright © 2005 - 2012 Pretty Klicks (prettyklicks.com)