To begin my page i do a check with facebook to get the login status of the user. I then create a namespace within the window object for use in other javascript files. Before I load any other javascript i need this namespace to be created, or else it will be undefined when i try to access it. Sometimes it completes first, and sometimes it does not. How can i make sure that it happens correctly every time?
.
.
.
FB.getLoginStatus(function(response) {
// store data on the user inside of a namespace
// inside of the window object so it can be accessed
// from anywhere. Use this like '$_SESSION'
console.log('doing it');
window.easyUserData = {
fbRespose: response,
site: <?php echo '"'.$site.'"'; ?>
};
})
};
(function(d) {
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document))
</script>
<!-- Load the script "js/main.js" as our entry point for require -->
<script data-main="js/main" src="lib/Require/require.js"></script>
specifically, i need the:
<script data-main="js/main" src="lib/Require/require.js"></script>
to not happen until the facebook function is complete
Move the code relying on the namespace into the Facebook callback. If it's the <script data-main="js/main" src="lib/Require/require.js"></script>, create the script element dynamically:
// ...
FB.getLoginStatus(function(response) {
// store data on the user inside of a namespace
// inside of the window object so it can be accessed
// from anywhere. Use this like '$_SESSION'
console.log('doing it');
window.easyUserData = {
fbRespose: response,
site: <?php echo '"'.$site.'"'; ?>
};
// Create the script element when ready
var script = document.createElement('script');
script.setAttribute("data-main", "js/main");
script.src = "lib/Require/require.js";
document.getElementsByTagName('script')[0].parentNode.appendChild(script);
// Or instead of `document.getElementsByTagName('script')[0].parentNode`
// you can use `document.documentElement` or `document.getElementsByTagName('head')[0]
// or a few others
})
};
You could move it all to one place as TJ suggests. Or you could check to see if your variable is created before attempting to run your own code:
// First this:
FB.getLoginStatus(function(response) {
window.easyUserData = {
fbRespose: response,
site: <?php echo '"'.$site.'"'; ?>
};
});
// Later in the code:
(function () {
var isFBLoaded = function () {
// If FB has loaded - run our code
if (window.easyUserData) {
myOtherFBStuff();
}
// If not - check again in 500 ms
else {
setTimeout(isFBLoaded, 500);
}
};
var myOtherFBStuff = function () {
// do stuff here
};
isFBLoaded();
})();
Related
i have the following js code but it does not work, i've tryed too much but no success:
•i already have a non expire full access token
•i have all permisions
<html>
<head>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<title>Invite</title>
</head>
<body>
<A href="#" onMouseOver="return changeImage()" ><img
name="jsbutton" src="http://cdn.property118.com/wp-content/uploads/2014/06 /Invite- friends-to-read-Property118-.jpeg" width="110" height="28" border="0"
alt="javascript button"></A>
<SCRIPT language="JavaScript">
window.fbAsyncInit = function() {
FB.init({ appId: xxxxxxxx,
status: true,
cookie: true,
xfbml: true,
oauth: true
version : 'v2.1'
});
};
(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.getLoginStatus(function(response) {
if (response.status === 'connected') {
function renderMFS() {
// First get the list of friends for this user with the Graph API
FB.api('/me/invitable_friends?limit=3000&access_token="I already have a non expire full user access token",
function(response) {
var container = document.getElementById('mfs');
var mfsForm = document.createElement('form');
mfsForm.id = 'mfsForm';
// Iterate through the array of friends object and create a checkbox for each one.
for(var i = 0; i < Math.min(response.data.length, 10); i++) {
var friendItem = document.createElement('div');
friendItem.id = 'friend_' + response.data[i].id;
friendItem.innerHTML = '<input type="checkbox" name="friends" value="'
+ response.data[i].id
+ '" />' + response.data[i].name;
mfsForm.appendChild(friendItem);
}
container.appendChild(mfsForm);
// Create a button to send the Request(s)
var sendButton = document.createElement('input');
sendButton.type = 'button';
sendButton.value = 'Send Request';
sendButton.onclick = sendRequest;
mfsForm.appendChild(sendButton);
});
}
}
});
</SCRIPT>
<div id="fb-root"></div>
</body>
</html>
i want my code show something like this Example but when I click the botton nothing happens. thanks in advance
First of all, there is no non expiring User Access Token, an Extended User Token is valid for 60 days. But in any case, you don´t need to worry about Access Tokens while using the JavaScript SDK, because it takes care of the User Token for you.
That being said, there are a LOT of problems in that code:
The biggest problem is that you don´t have any authorization routine. Use FB.login to authorize users. And again, don´t worry about Access Tokens.
You are trying to use the synchronous AND the asynchronous way to include the JavaScript SDK. Always use the asynchronous way and forget about the synchronous way.
You are using FB.getLoginStatus and FB.api before initializing the JS SDK with FB.init. The whole block of code with FB.getLoginStatus should be either right after FB.init or in a function that is called on user interaction (mouse click).
That link does not do anything. There is no changeImage function anywhere in your code.
There is also no sendRequest function anywhere, and you are trying to call that function with that input button.
Just open your browser console and you may see some errors pointing some of those things out.
Btw, here´s an article about how to use the JS SDK in a proper way: http://www.devils-heaven.com/facebook-javascript-sdk-login/
If you view this question thank you in advance!, I am working on pulling data from Facebook.
I am trying to pull the username from Facebook so i can use it in a later stage I have embedded the following code in the FB Root div.
I know the retrieve works! however i am not able to pass it on to the function returndata I am relative new to javascript could you please help me out? i have tried everything
There is an alert in there to check if it is retrieving data
<div id="fb-root"></div>
<script type="text/javascript">
$(document).ready(function()
{
var appId = "121070974711874";
// If logging in as a Facebook canvas application use this URL.
var redirectUrl = "http://apps.facebook.com/bggressive";
// If logging in as a website do this. Be sure to add the host to your application's App Domain list.
var redirectUrl = window.location.href;
// If the user did not grant the app authorization go ahead and tell them that. Stop code execution.
if (0 <= window.location.href.indexOf ("error_reason"))
{
$(document.body).append ("<p>Authorization denied!</p>");
return;
}
// When the Facebook SDK script has finished loading init the
// SDK and then get the login status of the user. The status is
// reported in the handler.
window.fbAsyncInit = function()
{
FB.init({
appId : appId,
status : true,
cookie : true,
oauth : true
});
FB.getLoginStatus (onCheckLoginStatus);
};
(function(d)
{
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
function onCheckLoginStatus (response)
{
if (response.status != "connected")
{
top.location.href = "https://www.facebook.com/dialog/oauth?client_id=" + appId + "&redirect_uri=" + encodeURIComponent (redirectUrl) + "&scope=user_photos,friends_photos";
}
else
{
FB.api('/me', function(response)
{
PASON = response.username
alert(response.username)
});
}
}
});
function returndata()
{
get = PASON
return get
};
</script>
I think you are calling the function returndata() at any random point which you can't do. The reason is- the variable PASON is assigned value asynchronously. So, you have to code in such a way that you call returndata() after the value is assigned!
Its not quite clear what you are trying to do with the function returndata(). But, I hope your concept is clear now.
Hi I am writing a code to login the user through the facebook. I store all the function in a file along with other javascript function. I try calling login function from another javascript function and get following error: login is not defined. Here is the code for index.html
<html xmlns:fb="http://ogp.me/ns/fb#">
<head>
<script type="text/javascript" src="javascript.js"></script>
</head>
<body>
<div id="fb-root"></div>
Hi!
</body>
</html>
Here is javascript.js
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : '213443452146381', // App ID from the App Dashboard
channelUrl : '//http://abc.in/', // Channel File for x-domain communication
status : true, // check the login status upon init?
cookie : true, // set sessions cookies to allow your server to access the session?
xfbml : true // parse XFBML tags on this page?
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected')
{
alert('connected');
}
else if (response.status === 'not_authorized') {
alert('not_authorized');
login();
} else {
alert('chillonly');
login();
}
});
function login() {
FB.login(function(response) {
if (response.authResponse) {
alert('connected');
testAPI();
} else {
alert('not_connected_login');
testAPI();
}
});
}
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
}
// Additional initialization code such as adding Event Listeners goes here
};
// Load the SDK's source Asynchronously
// Note that the debug version is being actively developed and might
// contain some type checks that are overly strict.
// Please report such bugs using the bugs tool.
(function(d, debug){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all" + (debug ? "/debug" : "") + ".js";
ref.parentNode.insertBefore(js, ref);
}(document, /*debug*/ false));
// ]]>
function sayhi()
{
alert('Hi');
login();
}
I doubt if the facebook jdk is getting loaded at all. Please suggest a way to achieve this.
The method login() is not accessible since it is in a local scope.
If you want function login() { to be used outside of that scope, you need to make it global or part of some global namespace.
Change
function login() {
to
window.login = function () {
First of all, move the functions out of the window.fbAsyncInit. They are not accessible since in the local scope.
Then, you can have a flag that will only set to true when the JS-SDK is loaded, and you can "block" any process outside the window.fbAsyncInit till the flag is set. Something like:
var isLoaded = false;
window.fbAsyncInit = function()
{
isLoaded = true;
...
...
}
function myFunc(myVar)
{
if(isLoaded)
{
// Do FB related stuff
}
}
I am currently using the following code to get the email id of the user using my app
function get_id(cb){
FB.init({
appId : .......,
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.login(function(response) {
if (response.authResponse) {
var token = response.authResponse.accessToken;
alert(token);
accessToken = token;
FB.api('/me?access_token=' + token + '', function (response) {
cb(response.email);
});
}
},{scope: 'email'});
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
}; // ending of get_id()
get_id(function (email) {
userID=email;
alert(email);
});
the current code is in a separate javascript file and this function is called when a button is pressed , I have also included <script src="http://connect.facebook.net/en_US/all.js"></script> in the HTML file . my browser (google chrome) gives me the following error each time I try and access it
"Uncaught ReferenceError: FB is not defined "
I am relatively new to developing Facebook apps , so all the reference I have is the developers page at facebook , I am sure it is a small error but I just cant wrap my head around it , appreciate it if anybody could point out where I could be going wrong
Your code will not load correctly. This part:
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
Should not be inside any function, put this in a script tag, after the body opening. It can't be in a separate file. This only does a async-load of all.js, that is the Facebook's JS SDK. If you are using the async-load, you should not put <script src="http://connect.facebook.net/en_US/all.js"></script> in your document, because this will do a sync-load.
This other part of your code:
FB.init({
appId : .......,
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
Also should not be inside the function. This fragment is responsible for starting the FB JS SDK in your page, with your app information, it only have to be called one time for each page, otherwise you will be starting the engine multiple times and it will have a caotic behavior. The "FB" object will only be created after the FB JS SDK loads. You don't know when it's going to happen, because of the async load. So you must assign the FB.init to this window event:
window.fbAsyncInit = function() {
FB.init({
appId : .......,
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
};
You want to create a get_id function that uses the Facebook information. You have to be careful with that. With you are sure that this function will be called after the complete load of FB JS SDK, you can create it in any part of your page. BUT I think the most safe way is to create it inside the window.fbAsyncInit. Don't worry about the token, the SDK does it for you:
window.fbAsyncInit = function() {
FB.init({
appId : .......,
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
function get_id(cb){
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function (response) {
cb(response.email);
});
}
},{scope: 'email'});
}
};
But when you do that, you will be not sure if your function was already created or not. So when you call it, you will have to test for it's existence:
if(get_id && typeof get_id == 'function') {
// It's safe to call your function, go ahead
get_id(function (email) {
userID=email;
alert(email);
});
} else {
// Your function does not exists yet, do other stuff
}
Good luck!
You need to put:
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
out of get_id function. So it was called before you press the button
PS: you don't need to pass ?access_token= manually - FB JS SDK does that for you
Im using facebook javaSDK for my website and I have a weird problem.
When I load the website with "internet explorer" it always runs fine.
When I load the website with firefox it always loads TWICE, and when I use chrome the JSDK sometimes loads once and sometimes not loads at all , giving me the error "Uncaught ReferenceError: FB is not defined ".
I tried using asynchronous loading for the SDK but still the same problem.
btw I have firebug on firefox, could that be the reason the JSDK loads twice?
this is the code for loading the jssdk
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '108437552626598', // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
</script>
And Im trying to use FB.getlogin, im trying to integrete facebook opengraph in Wordpress site. Ive out my script right after I finish loading the main content
This is the code
</div><!-- end #content -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
FB.getLoginStatus(function(response) {
if (response.status == 'connected') {
alert('in');
window.facebooklogin = 'true';
window.myValue = response.authResponse.accessToken;
window.myId = response.authResponse.userID;
$('.userimage img').attr('src','http://graph.facebook.com/' + window.myId + '/picture');
$.ajax({ url: 'http://ballvids.com/check/admin_checkuser.php',
data: {action: window.myId},
dataType:'json',
type: 'post',
success: function(output) {
if (output.message == 'true'){
$('.thumbnail img').attr('src',"http://ballvids.com/images/on2.png");
alert(window.myValue);
FB.api('/me/video.watches?video=<?php echo urlencode(get_permalink($post->ID));?>&access_token='+window.myValue,'post',function(response) {
if (!response || response.error) {
alert(response.error.message);
} else {
alert(response.id);
postID=response.id;
showStuff('removeTimeline');
}
});
}else{
$('.thumbnail img').attr('src',"http://ballvids.com/images/off2.png");
}
}
});
}else{
alert('inside2');
$('.thumbnail img').attr('src',"http://ballvids.com/images/off2.png");
window.facebooklogin = 'false';
}
},true);
Thanks
You have to call the FBLoginStatus(), inside the fbAsyncInit
window.fbAsyncInit = function() {
FB.init({
appId : APP_ID,
status : true,
cookie : true,
xfbml : true
});
FB.getLoginStatus( function(response) {
console.log(response);
}, true);
};
If you have problems with the cached object returned from the FB.getLoginStatus() you have to pass a second parameter true.
Documentation: https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
When I load the website with firefox it always loads TWICE,
Try setting up a channel.html file and referencing it on initialization.
and when I use chrome the JSDK sometimes loads once and sometimes not loads at all , giving me the error "Uncaught ReferenceError: FB is not defined ".
If you had your calls to FB methods wrapped into window.fbAsyncInit that would not be possible, because that callback would never be called if the SDK wasn’t loaded. Conclusion: You didn’t, but instead you put your FB.getLoginStatus call somewhere else (which you still haven’t shown us in your code yet).