Reputation: 39
I followed the instructions on getting started with using the Facebook API and can not figure out why I get the error
Uncaught ReferenceError: FB is not defined
This is my code
<body>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '627917414035377',
xfbml : true,
version : 'v2.7'
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
FB.api(
'/me',
'GET',
{"fields":"fan_count"},
function(response) {
// Insert your code here
console.log(response);
}
);
</script>
</body>
Upvotes: 0
Views: 101
Reputation: 96151
When loading the SDK this way, you need to wait until it has properly initialized (which happens by the FB.init call inside the fbAsyncInit event handler) before you can further use the FB object.
If you just want to make an automatic API call on page load, without any user interaction – then simply place the call inside the fbAsyncInit handler function, after FB.init:
window.fbAsyncInit = function() {
FB.init({
// …
});
FB.api({
// …
});
};
Although, without having the user login first, you might just get an error saying that the API call needs an access token.
Plus, when you are making this request on every page load, you might run into the API Rate Limits pretty soon.
You should rather do this on the server side (using an app or page access token), and implement some form of caching, so that you don’t have to make an API request on every page load.
Upvotes: 1