Javascript asynchronous - javascript

I have some 3 methods.
login();
isLogin();
reply();
function isLogin(){
FB.getLoginStatus(function(response) {
if (response.session) {
// logged in and connected user, someone you know
} else {
// no user session available, someone you dont know
}
});
}
function login (){
FB.login(function(response) {
if (response.session) {
// user successfully logged in
} else {
// user cancelled login
}
});
}
function reply(){
var body = 'Reading Connect JS documentation';
FB.api('/me/feed', 'post', { body: body }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response);
}
});
}
I need, when a user will want to reply a comment then reply method will execute. before executing reply method it should test if user is login, if user is not login then execute login method and call reply method again. How can I achieve this task
Thanks in advance

you need to construct conditions that will handle the following:
When a user will want to reply a comment
Check session if user isLogin()
if TRUE then reply method is enabled by default
if FALSE then call login() method via ajax for awesomeness
if login.success then call reply method
if login.failed add statement here

Related

FaceBook JavaScript SDK no response is sent when login cancelled

I am working with the FaceBook JavaScript SDK to log users in via FaceBook SSO. documentation
Clicking the SSO button opens a new window prompting the user to log in via FaceBook. If the user logs in there is no issue. However, if the user exits or cancels the SSO, I am not getting a response from FB.
Here is the function given in the FB documentation:
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.');
}
});
I have tried using this function exactly and again if I cancel the SSO the else block never runs as I would expect it to.
I am trying to modify the function slightly but I still am not able to get a response when the page is cancelled.
static login(callbacks, { mode = "login" }) {
const FB = window.FB;
FB.login(
(res) => {
console.log(res);
const { authResponse } = res;
if (mode === "login") {
Facebook.socialSignOn(authResponse, callbacks);
} else if (mode === "verify") {
Facebook.socialVerify(authResponse, callbacks);
}
},
{ return_scopes: "true", scope: "email" }
);
}
UPDATE
After playing around more it seems like if I try to use the FB SSO, cancel, and then try again all future FB.login() attempts immediately receive a response with authResponse : null

Facebook Js Sdk, publish_actions not working

i'm using javascript sdk and i have already send to review my publish_action , they are approved. Anyway i can't publish my post , the way i require the scope is this:
FB.login(function(response)
{
...
}, {scope: 'email,publish_actions'});
When i try to publish the return error is:
(#200) The user hasn't authorized the application to perform this action
It's true, because in the facebook modal login, appears only the permission to read information of the profile, no the permission to publish. How i can solve?
EDIT
i add my complete code to better explain:
<script type="text/javascript">
/***FACEBOOK***/
function fb_publish_Photo(immaginelink,idfoto){
var testo_share= $("#share_text").text();
var wallPost = {
message: testo_share,
link:immaginelink,
picture:immaginelink
};
console.log(wallPost);
FB.api('/me/feed', 'post', wallPost , function(response) {
if (!response || response.error) {
console.log(response.error);
alert('Failure! ' + response.error + ' You may logout once and try again');
} else {
// alert('Success! Post ID: ' + response.id);
var PostId=response.id;
if(response.id!=null && response.id!=''){
FB.getLoginStatus(function (response) {
if (response.authResponse) {
} else {
// do something...maybe show a login prompt
}
}, {scope: 'publish_actions'});
}
}
console.log(response);
}, { scope: 'publish_actions'});
}
function statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(response);
// The response object is returned with a status field that lets the
// app know the current login status of the person.
// Full docs on the response object can be found in the documentation
// for FB.getLoginStatus().
if (response.status === 'connected') {
// Logged into your app and Facebook.
//fb_login();
} else if (response.status === 'not_authorized') {
} else {
}
}
function fb_login(){
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?fields=email,first_name,last_name,name', function(response) {
//chiamata ajax per registrare/loggare l'utente
console.log(response);
});
} else {
//user hit cancel button
console.log('User cancelled login or did not fully authorize.');
}
}, {
scope: 'publish_actions'
});
}
// This function is called when someone finishes with the Login
// Button. See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxxxxx',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.4' // use version 2.4
});
// Now that we've initialized the JavaScript SDK, we call
// FB.getLoginStatus(). This function gets the state of the
// person visiting this page and can return one of three states to
// the callback you provide. They can be:
//
// 1. Logged into your app ('connected')
// 2. Logged into Facebook, but not your app ('not_authorized')
// 3. Not logged into Facebook and can't tell if they are logged into
// your app or not.
//
// These three cases are handled in the callback function.
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
// Load the SDK asynchronously
(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'));
/***end FB***/
</script>
EDIT
This is the only ref i can find in facebook documentation:
function myFacebookLogin() {
FB.login(function(){}, {scope: 'publish_actions'});
}
or
FB.login(function(){
// Note: The call will only work if you accept the permission request
FB.api('/me/feed', 'post', {message: 'Hello, world!'});
}, {scope: 'publish_actions'});
It seems simple, in login call i have to require permission, so why the publish permission dialog not appears in an approved app?
EDIT
this is a screen of my app permission
Publish_actions scope now seems to works correctly. I had two times scope request.

Logout in Facebook SDK Javascript

In my app I can log in to Facebook but I can't logout. When I click button which call logout function I get:
Object { authResponse: null, status: "unknown" }
Here is my code:
function login_to_fb() {
FB.login(function(response) {
if (response.status === 'connected') {
window.location.reload();
}
}, {
scope: 'email'
});
}
function logout_from_fb() {
FB.getLoginStatus(function(response) {
console.log(response);
if (response && response.status === 'connected') {
FB.logout(function(response) {
window.location.reload();
});
}
});
}
I figured out it's because I refresh the page. Without it, scripts works fine but when I log-in and refresh the page then log-out is impossible. How can I save it?
It is possible that the result is cached. Try passing true as the second argument to clear the cache:
FB.getLoginStatus(function(response) {
// this will be called when the roundtrip to Facebook has completed
}, true);

How to return access token facebook?

I don't know how to sync in api FB.login and here is my code:
function getAccesToken(){
var access_token = "";
FB.login(function(response) {
if (response.authResponse) {
access_token = FB.getAuthResponse()['accessToken'];
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, { scope: '' });
return access_token;
}
when I call function
var access_token = getAccessToken();
but it return empty string. How can I fix it to be synchronous?
You can't make this synchronous - and it would be extremely bad practice if you could. Instead, call a function in the FB.login callback handler that contains the access token. Try this:
function getAccesToken() {
FB.login(function(response) {
if (response.authResponse) {
loginComplete(FB.getAuthResponse()['accessToken']);
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, { scope: '' });
}
function loginComplete(token) {
console.log(token);
// do something here, now the user is logged in...
}
FB.login needs to be called on user interaction (mouse click) and you have to use the callback function of FB.login to get the Access Token asynchronously - the Access Token will be in the response value. For example:
document.getElementById('loginBtn').addEventListener('click', function() {
FB.login(function(response) {
if (response.authResponse) {
doSomethingWithTheToken(response.authResponse.accessToken);
}
}, {scope: 'email,public_profile', return_scopes: true});
}, false);
function doSomethingWithTheToken(token) {
console.log(token);
}
Source (and a lot more information about the JavaScript SDK): http://www.devils-heaven.com/facebook-javascript-sdk-login/

Facebook login function doesn't executes anything after the login itself

In the following code, I try after the login to execute ajax and redirect,
What is utterly weird is, that it logs me in, but anything that comes after the FB.login is ignored!
also I use this exact code in another site and it works fine, withe the ajax and the redirect.
The call to facebook api as asynchronous, and is not included here (it works)
$(".joiner").live("click", login);
var button = document.getElementById('fb-login');
window.fbAsyncInit = function() {
FB.init({appId: '0000000000000000', status: true});
FB.getLoginStatus(function(response) {
if (response.session) {
console.log('User is logged in.');
FB.api("/me", handleMe);
}
else {
console.log('User is not logged in.');
}
});
};
function login(){
FB.login(function(response) {
if (response.session) {
console.log('Login success.');
FB.api("/me", handleMe);
}
else {console.log('Login cancelled.')}
});
}
function handleMe(response) {
$.ajax({
type: 'GET',
url: 'www.url.com',
data: "uid=" + response.id + "&name=" + response.name + "&gender=" + response.gender,
success: function(){
console.log('Ajax successful.');
window.location = "www.url.com";
},
error: function(){console.log('Ajax failed.');}
});
}
I had this problem some time ago. I could solve it with seting the right url in the facebook app configuration and running the script from this url. It does not work when you try to make a login from, for example, your localhost with a diffrent url setting in the app config.
there is an respone showing the error code, but not response.session.

Categories