Get Facebook profile picture using API and jQuery

This shows how to fetch the users profile information directly to your web page using the Facebook API and jQuery (for updating the HTML).

First step is to register your web site as a Facebook app. You will need a Facebook account in order to access the development features.



If you're doing local development be sure to set the URL to your local path, otherwise you'll get an error saying: API Error Code: 191
API Error Description: The specified URL is not owned by the application


Once signed up your new Facebook app will get an App ID assigned. You need to copy that into the script below where it says xxxxxxxxxxxxxxxxx.

Most of the code below should be self explaining, but this is what it does:
1) Init a connection to Facebook with your app id
2) Get login status and..
3a) Show connect button if not connected
3b) Show profile information if connected

<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>

<h2>Profile</h2>
<div id="account-info"></div>

<script>
function showAccountInfo() {
FB.api({
method: 'fql.query',
query: 'SELECT name, pic FROM user WHERE uid=' + FB.getSession().uid
},
function(response) {
$('#account-info').html('<img src="' + response[0].pic + '">' +
response[0].name + ' <img onclick="FB.logout()" style="cursor: pointer;" ' +
'src="https://s-static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif">');
}
);
}

function showLoginButton() {
$('#account-info').html('<img onclick="FB.login()" style="cursor: pointer;" ' +
'src="https://s-static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif">');
}

// Called when Facebook login status change
function onStatus(response) {
if (response.session) {
showAccountInfo();
} else {
showLoginButton();
}
}
FB.init({
appId: 'xxxxxxxxxxxxxxxxx',
cookie: true,
status: true,
xfbml: true
});

FB.getLoginStatus(function(response) {
onStatus(response); // once on page load
FB.Event.subscribe('auth.statusChange', onStatus); // every status change
});

</script>

You can access other profile information as well. You'll find all properties on the user object over at Facebook Query Language (FQL) Reference.

If you're getting an unspecified error when trying to connect a user to your web page, the most likely issue is that you're app is in sandbox mode which blocks the app for other users than the developer. You can turn it off under settings over at your Facebook app page.

Related posts:

Comments

comments powered by Disqus