Facebook login/logout website - javascript

I am trying to integrate facebook login logout in my website using facebook's PHP JS sdk. My problem is I cannot implement an independent login/logout option from actual facebook site. When I click the login button, it actually logs in the user's facebook and also my site. But, on clicking my site's logout button, It just logout from my site because I could only destroy my session. If I use autologoutlink="true" then it show the facebook logout button when logged in, but it does the logout of the actual facebook. I want to implement something like www.9gag.com.
I would really appreciate some help.
Here is my code, I am using CodeIgniter, and putting everything in the view/header.php .
?php
require 'src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'app_id',
'secret' => 'secret_key',
));
// See if there is a user from a cookie
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
//echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
?>
<fb:login-button scope="email" autologoutlink="true" ></fb:login-button>
JS
<script>
window.fbAsyncInit = function() {
FB.init({
appId: '<?php echo $facebook->getAppID() ?>',
channelUrl : 'site_url',
cookie: true,
logging: true,
status: true,
xfbml: true,
oauth: true
});
FB.Event.subscribe('auth.login', function(response) {
FB.api('/me', function(userInfo) {
//console.log(userInfo);
var options_ = {
'responsedata' : userInfo,
}
$.ajax({
type: 'POST',
url: 'user/facebooklogin',
data: options_,
dataType: "text",
success: function(msg){
console.log(msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
});
}, {scope: 'email,user_likes'});
});
FB.Event.subscribe('auth.logout', function(response) {
window.location.reload();
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>

Related

Email not able to retrieve from facebook javascript SDK [duplicate]

I am using JavaScript API to create my app for Facebook. The problem is, it's returning
email = undefined.
I don't know why? And if I use Facebook login/logout button on my app then the alert shows correct email id of the user but I don't want to do that.
What am I missing?
Here is my code:
<p><fb:login-button autologoutlink="true" perms="user_about_me,email"></fb:login-button></p>
<script>
window.fbAsyncInit = function () {
FB.init({ appId: '250180631699888', status: true, cookie: true,
xfbml: true
});
FB.getLoginStatus(function (response) {
if (response.session) {
greet();
}
});
};
(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);
} ());
function greet() {
FB.api('/me', function (response) {
alert('Welcome, ' + response.name + "!");
alert('Your email id is : '+ response.email);
});
}
</script>
// https://developers.facebook.com/docs/javascript/reference/FB.api/
// v2.4
FB.api('/me', { locale: 'en_US', fields: 'name, email' },
function(response) {
console.log(response.email);
}
);
here is example how i retrieve user name and e-mail:
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
$(function() {
FB.init({
appId : 'APP_ID',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.getLoginStatus(function(response) {
if (response.status == 'connected') {
getCurrentUserInfo(response)
} else {
FB.login(function(response) {
if (response.authResponse){
getCurrentUserInfo(response)
} else {
console.log('Auth cancelled.')
}
}, { scope: 'email' });
}
});
function getCurrentUserInfo() {
FB.api('/me', function(userInfo) {
console.log(userInfo.name + ': ' + userInfo.email);
});
}
});
</script>
According to the latest info on the facebook page you should use 'scope' instead of perms.
https://developers.facebook.com/docs/reference/javascript/FB.login/
If you visit
https://developers.facebook.com/tools/console/
and use the fb-api -> user-info example as a starting point, then logout and back in again, it should ask you for email perms and you can see your email being printed. It is done using response.email as you mention in your post.
<button id="fb-login">Login & Permissions</button>
<script>
document.getElementById('fb-login').onclick = function() {
var cb = function(response) {
Log.info('FB.login callback', response);
if (response.status === 'connected') {
Log.info('User logged in');
} else {
Log.info('User is logged out');
}
};
FB.login(cb, { scope: 'email' });
};
</script>
Use this to for extra permission
for more details visit :
https://www.fbrell.com/examples/
In this code i have get user data form facebook and store into my database using ajax
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me?fields=email,name,first_name,last_name', function(response)
{
FB.api(
"/"+response.id+"/picture?height=100",
function (responses) {
//console.log(responses.data.url)
response['profile_pic']=responses.data.url;
$.ajax({
type:"POST",
url:'<?php echo base_url(); ?>'+'home/facebook_get_signup',
data:response,
success:function(res)
{
if(res=='success')
{
window.location='<?php echo base_url(); ?>';
}
if(res=='exists')
{
window.location='<?php echo base_url(); ?>';
}
}
});
}
)
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
// handle the response
}, {scope: 'email,user_likes'});
There are a couple of things wrong with your solution. First of all you are using the old authentication scheme. You should use the new one described here :
https://developers.facebook.com/docs/reference/javascript/
You need to add the oauth:true to your init function, and make sure that your getLoginStatus looks for the new type of response.
When that is said you need to make sure you have the right permissions to see the users e-mail. You can see the required permissions here:
http://developers.facebook.com/docs/reference/api/user/
You get those by using the FB.login function as described by TommyBs in another answer.
Once you have those options you can use the FB.api function to get the e-mail.

Data is not going through the ajax code

I'm using Facebook login feature & transferring some variables to other page through ajax. This particular ajax code isn't working, data is not going through. However I've other ajax code in other pages that works pretty good.
I'm not able to find the defect in the code.
Here is the code:
Page where ajax is called
<script type='text/javascript'>
window.fbAsyncInit = function() {
FB.init({
appId : 'XXXXX',
status : false,
cookie : true,
xfbml : true
});
}
function Login()
{
FB.login(function(response) {
if (response.authResponse)
{
getUserInfo();
}
else
{
console.log('User cancelled login or did not fully authorize.');
}
},{scope:'email,public_profile'});
}
function getUserInfo() {
FB.api('/me/permissions', function(response) {
var permission_response = JSON.stringify(response);
var permissions = eval('('+permission_response+')');
$.ajax({
type: "POST",
url: "/ajax_save_facebook_data.php",
data: {permissions:permissions},
success: function(option){
alert(option); // Nothing coming here, blank alert
}
});
});
}
AJAX Page
$permissions=$_POST['permissions'];
echo $permissions;
Anybody can help in this? I will really appreciate it.
FB.api is asynchrone function, so your var permissions doesn't exist when you do your ajax call.
Try:
function getUserInfo() {
FB.api('/me/permissions', function(response) {
var permission_response = JSON.stringify(response);
var permissions = eval('('+permission_response+')');
$.ajax({
type: "POST",
url: "/ajax_save_facebook_data.php",
data: {permissions:permissions},
success: function(option){
alert(option); // Nothing coming here, blank alert
}
});
});
}

Facebook Login Button callback function

I got a Problem with the Facebook Login on my Website. The Code Below is my FB-Connect Code. The commented part of the code sign's me in to my Website. My Problem is when i "reactivate" this code it logs me in instandly everytime i visit the page. But i want to log the user in when he clicks the "Login with Facebook"-Button. When I clicks the facebook login button a Popup shows up and nothing happens..
Can i somehow call a JS function when i click the FB-Connect button?
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxxxxxxxxxxxx', // App ID
status : true,
cookie : true,
xfbml : true,
oauth : true,
});
var login = false;
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
console.log('connected');
login=true;
var uid = response.authResponse.userID;
//this part of the code below redircts me to the part, where i login to my system.
/*var accessToken = response.authResponse.accessToken;
$.ajax({
type: 'POST',
url: '/?eID=login',
data: $(this).serialize(),
success: function(msg) {
alert("LOGIN");
$('#content').load('/live-session/tickets/');
}
});*/
}});
You need to use FB.login function on click on fb connect button and don't use FB.getLoginStatus
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 + '.');
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
});
From Doc
FB.getLoginStatus allows you to determine if a user is logged in to
Facebook and has authenticated your app.
So, if you don't want to check whether user has logged in on page load, don't call this
When I clicks the facebook login button a Popup shows up and nothing happens..
If you had already authorized the app and authenticated, facebook wont ask you again for login and authorization

Facebook login JS - FB.Event.subscribe('auth.login') triggers without login button click

really need your help with log-in-with-facebook feature I'm trying to implement on my website.
Basically, I'm trying to achieve the following:
if user has acknowledged the app before and clicks FB Log in button
on my website, they get logged into the website (with website's user
account associated with the Facebook user ID)
if user has not acknowledged the app before, on FB log in (and subscription to app) they get redirected to website's registration page. Here the form is pre-filled with user data
coming through Facebook and registration process becomes easier and faster.
I'm using the code below.
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId: 'xxxxxxxx',
status: true,
cookie: true,
xfbml: true,
oauth: true
});
FB.Event.subscribe('auth.login', function(response) {
if (response.status === 'connected') {
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
if ((parseFloat(uid) == parseInt(uid)) && !isNaN(uid)) {
$.ajax({
url: '/user_actions/prep_facebook_registration',
cache: false,
type: 'POST',
data: { 'uid': uid, 'token': accessToken },
dataType: 'json',
success: function(data) {
if (data.success=='true') {
if ((typeof(data.redirect) != 'undefined')) {
window.location=data.redirect;
}
}
}
});
}
}
});
FB.Event.subscribe('auth.logout', function(response) {
FB.getLoginStatus(function(res) {
if (!res.authResponse) {
window.location='/access/logout';
}
});
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
//not doing anything so far
}
});
};
(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/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
LogIn button lays further down in a website:
<div class="fb-login-button" autologoutlink="true" data-show-faces="false" data-width="166" data-max-rows="1" style="position: absolute; top: 5px; right: 0;" scope="email"></div>
The problem here is that FB.Event.subscribe('auth.login') triggers not only on FB log in button click, but also if user has logged to Facebook and only after comes to my website. This causing a redirection to registration page or current page reload even if user hasn't clicked the login button!
'/user_actions/prep_facebook_registration' holds a script, which is checking if the member has to be redirected to registration page or should be loggedin with local account. It returns the URL to redirect.
What am I doing wrong? How can I avoid FB.Event.subscribe('auth.login') being triggered outside the login button click?
Actualy, there's a better solution.
There are 2 things that you could do better:
In your FB.init method, you're setting status: true. This tells the page that it should check whether the user is logged in the facebook immediately after page loads. In your case, it's not only that you don't need it - it will take some of your visitor's bandwidth for round trip to facebook that you don't actually need.
You don't need to remember uid and accessToken variables since you can get them on demand by using FB.getLoginStatus method.
The complete solution based on your sample code would be:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR APP ID',
status : false,
cookie : true,
xfbml : true
});
};
(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 Facebook_login () {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
if ((parseFloat(uid) == parseInt(uid)) && !isNaN(uid)) {
$.ajax({
url: '/user_actions/prep_facebook_registration',
cache: false,
type: 'POST',
data: { 'uid': uid, 'token': accessToken },
dataType: 'json',
success: function(data) {
if (data.success=='true') {
if ((typeof(data.redirect) != 'undefined')) {
if (data.redirect=='current') {
location.reload();
} else {
window.location=data.redirect;
}
}
}
}
});
}
}
}
}
</script>
<div class="fb-login-button" onlogin="Facebook_login()" autologoutlink="true" [parameters]></div>
=====================
Edit: Ok, I think there's a bit of a progress here :)
I've extended the FB login button with onlogin event which calls a JS function Facebook_login()
<div class="fb-login-button" onlogin="Facebook_login()" autologoutlink="true" [parameters]></div>
I've exported uid and accessToken variables outside window.fbAsyncInit function so I could access them from anywhere else:
var uid;
var accessToken;
window.fbAsyncInit = function() {
FB.init({
your parameters
});
});
Then, I got FB.Event.subscribe('auth.login') to only assign values to my uid and accessToken variables, but not perform any redirection.
FB.Event.subscribe('auth.login', function(response) {
if (response.status === 'connected') {
uid = response.authResponse.userID;
accessToken = response.authResponse.accessToken;
}
});
And finally, my custom function Facebook_login () fetches the uid and accessToken values and does the rest of the operation. This time it happens only when login button is clicked. Please note, this function is outside window.fbAsyncInit()
function Facebook_login () {
if ((parseFloat(uid) == parseInt(uid)) && !isNaN(uid)) {
$.ajax({
url: '/user_actions/prep_facebook_registration',
cache: false,
type: 'POST',
data: { 'uid': uid, 'token': accessToken },
dataType: 'json',
success: function(data) {
if (data.success=='true') {
if ((typeof(data.redirect) != 'undefined')) {
if (data.redirect=='current') {
location.reload();
} else {
window.location=data.redirect;
}
}
}
}
});
}
}
This seems to do a job for me. If anyone has any better solutions, your input would be appreciated :)

How to get FB.api('/me/feed', 'post', ... to work?

I've tried to use FB.api to post something to my feed for hours now. I can't get it to work for me. I gave the permissions to the app. I can post to my feed with the PHP SDK but I have to use JavaScript.
<button onclick="doPost()">Post to Stream</button>
<script>
window.doPost = function() {
FB.api(
'/me/feed',
'post',
{ body: 'Trying the Graph' },
Log.info.bind('/me/feed POST callback')
);
};
</script>
Can someone give me the example of a simple HTML page that uses FB.api to post to a feed?
Well, I got it working myself. I'm not sure what was wrong the first time as I started from scratch with a new HTML file. I hope it will help someone:
<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
</head>
<body>
Post to Facebook
<script>
function postToFacebook() {
var body = 'Reading Connect JS documentation';
FB.api('/me/feed', 'post', { body: body, message: 'My message is ...' }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response);
}
});
}
</script>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR APP ID GOES HERE',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
};
(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);
}());
</script>
</body>
</html>
I use this code on fb game-app
and looks like this http://trupa.files.wordpress.com/2012/04/prscreenan.jpg
<br><font style="color:#FFF; text-decoration:none;padding-left:27px;">post to wall</font><br>
<script>
function publishStory() {
FB.ui({
method: 'feed',
name: 'message name',
caption: 'message caption ',
description: 'description goes here',
link: 'the url current page',
picture: 'if you want to add an image'
},
function(response) {
console.log('publishStory response: ', response);
});
return false;
}
</script>
In first example you forgot "message" property. With out "message" you can post everyone, but not self.

Categories

Resources