FB is not defined in Facebook Login

cdub picture cdub · Feb 1, 2012 · Viewed 38.2k times · Source

I have the following code but the FB.login gives a FB is not defined javascript error.

What am I missing?

<html>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function()
{
FB.init
({
    appId   :   'XXXX',
    status :    true,
    cookie :    true,
    xfbml   :   true
});
};

(function()
{
var e = document.createElement('script');
e.src = document.location.protocol +  '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());



FB.login(function(response)
{
if(response.session)
{
    if(response.perms)
    {
        alert('yippee');
    }
    else
    {
        alert('oh no');
    }
}
else
{
    alert('login silly');
}
}, {perms:'email,user_birthday'});


</script>
hello
<fb:login-button></fb:login>

</body>
</html>

Answer

Somnath Muluk picture Somnath Muluk · Feb 1, 2012

The function assigned to window.fbAsyncInit is run as soon as the SDK is loaded. Any code that you want to run after the SDK is loaded should be placed within this function and after the call to FB.init. For example, this is where you would test the logged in status of the user or subscribe to any Facebook events in which your application is interested.

Try by keeping other initialization code in between inialization and login function

Or keep FB.login code in $(document).ready

$(document).ready(function(){

FB.login(function(response)
{
if(response.session)
{
    if(response.perms)
    {
        alert('yippee');
    }
    else
    {
        alert('oh no');
    }
}
else
{
    alert('login silly');
}
}, {perms:'email,user_birthday'});

});