Accessing Facebook friends list fails when used with JavaScript SDK - javascript

I have been seeing questions on Stack Overflow to access the Facebook friends list of a user. I have tried in many different ways to do this and unfortunately nothing seems to be working for me.
Can any one tell me the exact problem I am facing? I'm totally new to javascript. Below is the code I am using
<html>
<head>
<title>My Facebook Login Page</title>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
var friends = new Array();
FB.init({
appId : 'some_id', // App ID
channelUrl : 'http://apps.facebook.com/myapp', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.api('/me/friends', function(response) {
if(response.data) {
$.each(response.data,function(index,friend) {
alert(friend.name + ' has id:' + friend.id);
});
} else {
alert("Error!");
}
});
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "http://connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
<p>
<fb:profile-pic uid='loggedinuser' facebook-logo='true'/>
</p>
</br>
</br>
"Welcome, <fb:name uid='' useyou='false'></fb:name>
</br>
</br>
</br>
</br>
</br>
</br></br> <fb:login-button autologoutlink="true" />
</body>
</html>
I am getting the response as undefined and am not able to even login to facebook. I tried using the following sample http://jobyj.in/api/get-facebook-friends-using-javascript-sdk/. This works fine with the Demo but then I downloaded it and tried to run from my machine it is also not giving me any result.
Any suggestions for me?
Update
I am using the example given by #Somnath below and able to login. But after that getting the value undefined for response.session resulting in zero friends list. Any idea for this?

Here is tutorial for login through javascript.
Tutorial Javascript SDK
Ist try to log in. Otherwise you will get undefined response.
FB.getLoginStatus(function(response) {
if (response.session) {
// logged in and connected user, someone you know
FB.api('/me/friends', function(response) {
if(response.data) {
$.each(response.data,function(index,friend) {
alert(friend.name + ' has id:' + friend.id);
});
} else {
alert("Error!");
}
});
}
});
You will get friend list of logged in user.
Updated Answer:
Don't specify channelUrl at time of initialization. Only give only following four parameters. Try this out.
FB.init({
appId : 'some_id', // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
Update2:
Try using fql:
if (response.session) {
//getting current logged in user's id from session object
globaluserid=response.session["uid"];
//fetching friends uids from 'friend' table. We are using FB.api syntax
FB.api(
{
method: 'fql.query',
query: 'SELECT uid1 FROM friend WHERE uid2='+globaluserid
},
function(response) {
//once we get the response of above select query we are going to parse them
for(i=0;i<response.length;i++)
{
//fetching name and square profile photo of each friends
FB.api(
{
method: 'fql.query',
query: 'SELECT name,pic_square FROM user WHERE uid='+response[i].uid1
},
function(response) {
//creating img tag with src from response and title as friend's name
htmlcontent='<img src='+response[0].pic_square+' title='+response[0].name+' />';
//appending to div based on id. for this line we included jquery
$("#friendslist").append(htmlcontent);
}
);
}
}
);
} else {
// no user session available, someone you dont know
top.location.href="../kfb_login.php";
}

Related

Facebook login response became "undefined" after putting code "window.location.href"

I'm implementing an application using Facebook login as an optional login approach. After the user logged in with the Facebook account, I write the username into a cookie and want to redirect to the index pager of the website. Everything works OK before I put the redirection code into the file. Here is the code. It's in javascript.
$(document).ready( function(){
window.fbAsyncInit = function() {
FB.init({
appId : 'myAppId',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.Event.subscribe('auth.authResponseChange', function(response) {
if (response.status === 'connected') {
var userName = testAPI(response);
var today = new Date();
var expire = new Date();
expire.setTime(today.getTime() + 3600000*24*30);
document.cookie="138do_uid="+userName+";expires="+expire.toGMTString()+"path=/";
window.location.assign("myWebpage");
} else if (response.status === 'not_authorized') {
FB.login();
} else {
FB.login();
}
});
};
// 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));
function testAPI(response) {
var myWindow = window.open("","MsgWindow","width=200,height=100");
var userName;
FB.api('/me', function(response) {
userName = response.name;
myWindow.document.write("<p>" + userName + "</p>");
});
return userName;
}
});
Before I added the line "window.location.assign("myWebpage");", the value of response.name is correct and the name is showed correctly in the pop-up window (The pop-up window is for testing). However, if I add the "window.location" line, the value of response.name suddenly becomes "undefined" and it also showed "undefined" in the pop-up window.
Anyone could tell me what the problem is?
Thanks,
Patrick
There are two major parts to this. The first one is your Facebook web app will only work on your domain space. So first I would try redirecting to a page on your domain space.
The second part is every page in you app that you want to use the Facebook API must have a Facebook object built on it and you have to verify that your user is logged in and they have granted your app the correct permissions to run whatever query you choose to run.
If you wish to expand further on the premise of your app I would be glad to help you out more.

facebook login error FB.login() called before FB.init()

i have a problem with loggin in into facebook i keep getting the error code: FB.login() called before FB.init(). i done various things but keep getting the error.
here's the html code:
<!-- Javascript
=================================================== -->
<script src="//connect.facebook.net/en_US/all.js"></script>
<script src="js/facebook.js"></script>
</head>
<body>
<div id="fb-root"></div>
<script>
var email;
var name;
window.fbAsyncInit = function()
{
FB.init({
appId : '509855929050339', // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.Event.subscribe('auth.login', function () {
window.location = "http://webs.hogent.be/~096506gd/home.html";
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
window.location = "http://webs.hogent.be/~096506gd/home.html";
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
} else {
// the user isn't logged in to Facebook.
}
});
};
// 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>
<div class="container">
<img class="offset-by-three ten columns margin-top25" src="images/logo.png">
<div class="offset-by-five">
<a class="six columns full-width button margin-top175" href="home.html">
Aanmelden
</a>
<a class="six columns full-width button margin-top175" onclick="loginUser()">
Aanmelden met facebook
</a>
</div>
</div>
</body>
</html>
and this is the javascript file:
function loginUser(){
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
//console.log(response); // dump complete info
access_token = response.authResponse.accessToken; //get access token
user_id = response.authResponse.userID; //get FB UID
FB.api('/me', function(response) {
alert ("email: "+response.email); //get user email
alert ("naam : "+respone.name);
// you can store this data into your database
});
} else {
//user hit cancel button
console.log('User cancelled login or did not fully authorize.');
}
}, {
scope: 'publish_stream,email'
});
}
In your code, you are including the Facebook JavaScript SDK three times! Remove the following lines:
<script src="//connect.facebook.net/en_US/all.js"></script>
and
<script id="facebook-jssdk" async="" src="//connect.facebook.net/en_US/all.js"></script>
Also, you may need to wait a second or two before Facebook is initialised, which could be another reason why you were getting the error.
Give it another go and hopefully it will work now.
Just put the app_id next to the js src
<script src="//connect.facebook.net/en_US/all.js&appId=xxxxxxxxxxxxxxx" type="text/javascript"></script>
That worked for me.

how to check whether user like my page or not using facebook JS SDK?

I am currently working in one facebook application which is going to run outside the facebook in one webpage having functionality of like page, but on bases of like i have to redirect page on different pages,
I tried lots of code to check whether user liked page already or not but failed.
So If any one knows how to check this than please help me.
Thanks in advance.
Note : Want to do only using JS SDK not PHP SDK.
To access the like data form facebook you need user_likes permission.
<div id="fb-root">
</div>
var page_id = 'YOUR PAGE / URL ID';
(function() {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
} ());
window.fbAsyncInit = function() {
FB.init({ appId: 'YOUR APP ID', status: true, cookie: true, xfbml: true, oauth: true });
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me/likes/' + page_id, function(api_response) {
try {
if ((api_response.data[0].name) != undefined)
alert(api_response.data[0].name);
else
alert('you are not like this page');
}
catch (e) {
alert('you are not like this page');
}
});
}
}, { scope: 'email,user_likes' });
};
You have to get user_likes permission, and then make a call to the Graph API requesting /me/likes/{facebook_id_of_your_URL}
That call returns a data array with your URL-objects data, or an empty data array if the user hasn’t liked it yet.

Facebook Integration Into Webpage

I am trying to integrate Facebook into my webpage so users can update their status from my site. Right now I have a button a user clicks to update their status, the button calls the updateFacebookStatus() function. When this button is clicked right now, a blank white window pops up saying "waiting for www.facebook.com". This window is where it should be asking for permission but the window just times out. Any ideas: Here is my code for the function updateFacebookStatus().
function updateFacebookStatus()
{
//Ask for permissions
FB.login(function(response)
{
}, {scope:'publish_stream, offline_access,manage_pages'});
FB.getLoginStatus(function(response)
{
//If user is logged it and given permissions update status
if (response.status === 'connected')
{
new_status = document.getElementById('FacebookBody').value;
//update status
FB.api(
{
method: 'status.set',
status: new_status
},
function(response)
{
if(response == 0)
{
alert("Your Facebook Status Was Not Updated.");
}
else
{
alert("Your Facebook Status Was Updated");
}
}
);}
else
{
window.location.href = "#home";
}
});
}
In my html file I get the Facebook javascript sdk using the following code:
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId : 'XXXXXXXXXXXXX',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
channelUrl : 'http://www.XXXXX.com/channel.html', // channel.html file
oauth : true // enable OAuth 2.0
});
// 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>
not sure if it has anything to do with your problem but notice that you call the same script twice - one time via <script src="http://connect.facebook.net/en_US/all.js"></script> tag and the other via async function call under // Load the SDK Asynchronously

JavaScript SDK Facebook: Trouble With Init Script

Trying to figure out how to use the JavaScript SDK. I'm new to JavaScrip. I was able to use the PHP SDK but want to run my stuff clientside. Anyhoo, I don't really understand the SDK documentation on the develop site. So the base code is:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID', // App ID
channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Additional initialization code here
};
// Load the SDK Asynchronously
(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));
Which I think I understand...it loads the SDK and then runs the FB.init stuff once it loads. I don't know where to put all of the OAuth stuff though, and how to structure the login request (i.e. if not logged in the make a button and if you are then return access token etc.
Can someone hold my hand through this beginning part. I've searched everywhere and I just don't quite get it.
Edit:
Okay, second try with authentication. Didn't work:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'XXX', // App ID
channelUrl : 'XXX', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Additional initialization code here
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and connected to your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
FB.api('/me', function(response) {
alert(response.name);
});
} else if (response.status === 'not_authorized') {
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
FB.logout(function(response) {
console.log('Logged out.');
});
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'email'});
} else {
}
})
};
// Load the SDK Asynchronously
(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));
</script>
Thanks!
Just below this line,
// Additional initialization code here
is where the oauth stuff goes.
I would suggest getting used to calling FB.getLoginStatus() first. See: http://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
EDIT
based upon the question edit above
This should be done inside the window.fbAsyncInit function
FB.api('/me', function(response) {
alert(response.name);
});
and only after you've checked the getLoginStatus() so you know if the person is logged in or not.

Categories