Extracting user id from Facebook Javascript SDK session object

Yev picture Yev · Mar 18, 2011 · Viewed 20.8k times · Source

I am using Facebook's Javascript SDK "FB.ui" to pull up an OAuth dialog. Once you click allow, I need to capture the session object, extract the user id and use it further in my script. For some reason I cannot get this working properly, I keep getting undefined, even though the session does exist.

<script src="http://connect.facebook.net/en_US/all.js"></script>
<div id="fb-root"></div>
<script type="text/javascript">
FB.init({
    appId  : '***************',
    status : true,
    cookie : true,
    xfbml  : true
});
FB.getLoginStatus(function(response) {
    if (response.session) {
        //do something
    } else {
        FB.ui({
            method: 'oauth',
            display: 'page',
            scope: 'email',
            perms: 'email'
        },
        function(response) {
            alert(response.session.uid); //returns underfined
        });
    }
});
</script>

Answer

Jamie Kitson picture Jamie Kitson · Jan 25, 2012

To get the userID:

FB.getLoginStatus(function(response) {
  alert(response.authResponse.userID);
});