Obtaining and Parsing Open Social Graph Data with JSONP and jQuery
Posted by Matt Cashatt on 4/25/2011 (Last updated on 4/25/2011 3:02 PM)

Sometimes you need an easy, client-side, method for grabbing information from Facebook's Open Social Graph, parsing the results, and then displaying the results on your page. Although Facebook's social plugins can do the trick in some situations, they don't always offer the flexibility you need "out of the box". This recipie will show you how to query the graph, parse the returned results, and finally place those results on your page.
Demo
Before getting started, take a look at the final product here.
Ingredients
· The latest version of jQuery (get it here).
Instructions
Step 1- Prepare your page
Start by adding a reference to jQuery in the head element of your html page:
<script type="text/javascript" src="scripts/jquery-1.5.2.min.js"></script>
Step 2- Add a few html elements
Here we are inserting a textbox, a button, and a placeholder div into which we will ultimately insert the response from our Open Social Graph call.
<h2>Enter the name of a large company and then press 'Go'.</h2> <input id="Company" type="text" /><input id="goButton" type="button" value="Go" /> <i>(examples: 'delta', 'nike', 'cocacola', 'bestbuy')</i> <div id="Placeholder"></div>
Step 3- Add jQuery for calling the open social graph:
We will be using jQuery's native .getJSON() method. At the bottom of your page (but within the body tags), place a set of script tags, and within them the following code:
//Add an event listner for the go button click:
$('#goButton').click(function () {
//Call the JSON feed from the Open Social Graph. Note the "&callback=?"
//querystring at the end of the url. This is important.
$.getJSON("https://graph.facebook.com/" + $('#Company').val() + "&callback=?",
//Once it is returned, do something with the JSON:
function (data) {
//Clear out the placeholder
$('#Placeholder').html("");
//Add some new data
$('#Placeholder').append("<h1>Company name:</h1>" + data.name + "<br/><br/>");
$('#Placeholder').append("<h1>Picture:</h1><img src=" + data.picture + " title=" + data.name + " /><br/><br/>");
$('#Placeholder').append("<h1>Facebook page:</h1>" + data.link + "<br/><br/>");
$('#Placeholder').append("<h1>Likes:</h1>" + data.likes + "<br/><br/>");
});
});
In the code above we did a few important things. First, we added an event listner that fires when the go button is clicked. Within that listner, we added a method to call the Open Social Graph and request information about an object which the user would have identified within the textbox.
IMPORTANT: Notice the "&callback=?" querystring in the Open Social Graph URL we are calling? This is extremely important when using jQuery to call the graph because it tells jQuery to interpret the request as JSONP (Javascript Object Notation with Padding) which circumvents cross scripting security checks and generally saves you a ton of time in coding.
Enjoy!
Comments


