How to store information from Facebook SDK login - javascript

I have attempted to implement the Facebook Javascript SDK login into my website but need to store information about the user so that when the user logs back in using Facebook I have information stored about them such as their previous in-website activities. Could I integrate this into a MySQL database?

I think you may searching for the following way of storing logged user information into mysql database,
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
var fbname=response.name;
var fbid=response.id;
$.ajax({
type: "POST",
url: page_for_storing_information,
data: "name="+fbname+"&uid="+fbid,
success: function(msg){
}
});
console.log('Good to see you, ' + response.name + '.');
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
});

Related

Facebook login callback returns name but not email address

I'm using Facebook login in the simplest way, and getting a call back response:
<div id="fb-root"></div>
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v6.0&appId=881911462250499&autoLogAppEvents=1"></script>
<script>
window.fbAsyncInit = function() {
FB.getLoginStatus(function(response) {
FB.api('/me', function (response) {
console.log(response);
});
});
}
</script>
I log the response to the console and receive the name and id, but not email address. How can I get the email as well? Upon researching it, it should get it by default, am I wrong?
According to the Fb docs, This is how you do it.
function statusChangeCallback(response) { // Called with the results from FB.getLoginStatus().
console.log('statusChangeCallback');
console.log(response); // The current login status of the person.
if (response.status === 'connected') { // Logged into your webpage and Facebook.
testAPI();
} else { // Not logged into your webpage or we are unable to tell.
document.getElementById('status').innerHTML = 'Please log ' +
'into this webpage.';
}
}
window.fbAsyncInit = function() {
FB.init({
appId : '{app-id}',
cookie : true, // Enable cookies to allow the server to access the session.
xfbml : true, // Parse social plugins on this webpage.
version : '{api-version}' // Use this Graph API version for this call.
});
FB.getLoginStatus(function(response) { // Called after the JS SDK has been initialized.
statusChangeCallback(response); // Returns the login status.
});
};
function testAPI() { // Testing Graph API after login. See statusChangeCallback() for when this call is made.
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.name);
document.getElementById('status').innerHTML =
'Thanks for logging in, ' + response.name + '!';
});
}
You can check login status in this way.
function checkLoginState() { // Called when a person is finished with the Login Button.
FB.getLoginStatus(function(response) { // See the onlogin handler
statusChangeCallback(response);
});
}
By default, fb allows only basic permissions. What you require is additional permission, hence you have to request it this way.
FB.login(function(response) {
// handle the response
}, {scope: 'email,user_likes'});
You can read more about it here. Hope it helps :)
Ok got it, I was confused and it shoudl be here:
FB.api('/me', { locale: 'tr_TR', fields: 'email,name' }, function (response) {

Can't get facebook user's email using facebook javascript sdk

I'm using facebook authentication on my website using javascript sdk. I can get my email and name but I can't get their email, if they're loging in, only their name (it's my fb developer app).
It asks for the login, in case no one is logged in on facebook yet but get nothing happens. If I put an alert where it's supposed to login to my app and it indeed returns the name, just not the email. But if it's me I get both. Why's that?
Here's my code:
<%-- Facebook conection script--%>
<script src="//connect.facebook.net/en_US/all.js"></script>
<script> FB.init({
appId: '334351783684824',
cookie: true,
xfbml: true,
version: 'v2.8'
});
function fbAuthUser() {
FB.login(checkLoginStatus);;
}
function checkLoginStatus(response) {
if (response.status === 'connected') {
FB.api('/me', 'GET', { fields: 'email,name' }, function (response) {
alert(response.email + "; " + response.name);
Ajax(response.email, response.name);
});
}
}
function Ajax(expressao1, expressao2) {
var request = { email: expressao1, nome: expressao2 }
$.ajax({
url: 'login.aspx/LoginExterno',
method: 'post',
contentType: 'application/json',
data: JSON.stringify(request),
dataType: 'json',
success: function (resp) {
window.location.href = resp.d;
},
error: function () { }
})
}
</script>
It's supposed to login and, after getting the data, use that ajax function to access a code behind c# function that redirects the user to the index, if he/she already has an account or to the registry if he/she doesn't have one. It doesn't even go in the Ajax function, because the email parameter is undefined, probably. But when both are present it does.
So, how can I get the email?
Ok, I finally got it. On on FB.Login function, I need to add the scope and the user has to give permission. On my code, it would be like:
FB.login(checkLoginStatus,{scope: 'email'});;

Facebook Api getting total count of friends, but not friends data

Hi I am using Facebook API javascript SDK, and trying to get logged in user friends data
Here is the scope i am using
FB.login(function(response) {
statusChangeCallback(response);
}, {
scope:'publish_actions,user_friends,public_profile',
return_scopes: true
});
FB.api('/me', function(response) {
$textInput = document.getElementById("searchText");
var request = jQuery.ajax({
type: "POST",
url: "/logged/ajax/facebook",
data: response });
request.done(function( $data ) {
jQuery(".loadingContent").css( "display", "none" );
if($data == "success"){
FB.api('/me/friends', function(data) {
console.log(data);
});
} else {
alert($data);
}
});
request.fail(function( jqXHR, textStatus ) {
});
});
but it returns me
({"data":[],"summary":{"total_count":79}})
data is always empty, though i am getting total count of my facebook friends
Since v2.0, you can only get friends who authorized your App too.
Check out the changelog for more information: https://developers.facebook.com/docs/apps/changelog
This question is also answered in several other threads already:
Get facebook friends with Graph API v.2.0
Facebook Graph Api v2.0+ - /me/friends returns empty, or only friends who also use my app
Get ALL User Friends Using Facebook Graph API - Android

Post Photo to Facebook Page not associated with User

I am building a website that will allow any authenticated Facebook user to post photos to a specific album associated with a Facebook page. I am using the JavaScript SDK for this task. This is the code I have so far:
window.fbAsyncInit = function () {
FB.init({
appId: "492414284132122",
status: true,
cookie: true,
xfbml: true,
channelUrl: "http://wineoclock.dev.mag/ClockMoments/channel.html"
});
};
function uploadPhoto() {
console.log("called uploadPhoto()...");
FB.login(function (response) {
if (response.authResponse) {
document.getElementById("access_token").value = FB.getAuthResponse()["accessToken'];
var form = document.getElementById("fbPhotoUpload");
var formData = new FormData(form);
// indicate to user that upload is in progress
document.getElementById("btnUpload").value = "Posting...";
document.getElementById("btnUpload").disabled = true;
// post photo to Facebook
$.ajax({
type: "POST",
// post to "Timeline Photos" album
url: "https://graph.facebook.com/283773431737369/photos",
data: formData,
cache: false,
contentType: false,
processData: false,
dataType: "json",
success: function (response, status, jqXHR) {
console.log("Status: " + status);
if (!response || response.error) {
alert("Error occured:" + response.error.message);
}
else {
document.getElementById("fbPhotoUpload").reset();
$("#ThanksModal").reveal();
}
document.getElementById("btnUpload").value = "Post Photo";
document.getElementById("btnUpload").disabled = false;
},
error: function (jqXHR, status, errorThrown) {
console.log("AJAX call error. " + status);
console.log("errorThrown: " + errorThrown);
},
complete: function (jqXHR, status) {
console.log("AJAX call complete. " + status);
}
});
}
else {
alert("Login failed: " + response.error);
}
});
}
Running the code above, I discovered that the selected image gets uploaded, but it is uploaded to Facebook account that is logged in. This is not what I wanted. I wanted to upload it to the target fan page (designated in the AJAX POST request), instead of the logged in user.
I have read on the Internet that I need to request a page access token, instead of a user access token. To do so I would need to log in as the target page, as described in the Facebook doc here.
Is there a way to retrieve the page access token without having to login as the administrator of the Facebook page? If required, can the login be done behind-the-scenes?
EDIT:
I think i misunderstood You; the process described at link i posted results in getting access token for ANY user, you only have to do this once.
I do strongly believe that this is not possible; if it would be doable, practically any app could post at any fanpage.
According to solution from here:Extending Facebook Page Access Token, You need have administrator privileges to convert your short-lived page access token to a long-lived (2 months actually instead of couple of hours). The whole process is well described at the link.

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

Categories

Resources