Don't load until function finishes loading - javascript

I'm pulling album photos from Facebook API and then arranging them in masonry style. I have it set up so that I'll run the API function, then when I click a button it'll run the masonry function, which works fine. Now what I want to do is have the masonry run automatically after all the images are downloaded, like so:
function fbAPI() {
//downloading photos and placing them in a div
masonryFunction();
}
function masonryFunction(){
//run the masonry plugin
}
The trouble I run into though is masonryFunction runs well before fbAPI has finished doing it's thing, which prevents it from working (all the photos must be loaded up first). Now I can't simply have masonryFunction run when the page is loaded because fbAPI doesn't get launched until after some user input. What can I do?

Call the fbAPI() function in the callback function for the FB login function.
For example,
FB.login(function(response) {
if (response.authResponse) {
facebookLoggedIn();
} else {
alert('User cancelled login or did not fully authorize.');
}
});
function facebookLoggedIn() {
fbAPI();
}
Or, subscribe to FB auth.statusChange event:
FB.Event.subscribe('auth.statusChange', function(response) {
facebookStatusChange(response);
});
function facebookStatusChange(response) {
if (response.status === 'connected') {
uid = response.authResponse.userID;
accessToken = response.authResponse.accessToken;
facebookLoggedIn();
} 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.
}
}

Related

How do I keep a user logged in my website?

I am using Facebook API to log in a user. It logs in a user successfully.
But whenever I refresh the website or close it then reopen it logs out automatically. I don't need that I want a user logged in until he himself logs out of my website. How do I do it?
This is my code:
function statusChangeCallback(response) {
if (response.status === 'connected') {
setElements(true);
console.log('Logged in');
instaInfo();
} else {
setElements(false);
console.log('not logged in');
}
}
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
function setElements(isLoggedIn) {
if (isLoggedIn) {
document.querySelector('#fb-btn').style.display = 'none';
document.querySelector('.logout').style.display = 'block';
document.querySelector('.navigation').style.display = 'block';
document.querySelector('.nav-main').style.visibility = 'visible';
document.querySelector('#container').style.display = 'block';
} else {
document.querySelector('#fb-btn').style.display = 'block';
document.querySelector('.logout').style.display = 'none';
document.querySelector('.navigation').style.display = 'none';
document.querySelector('.nav-main').style.visibility = 'hidden';
document.querySelector('#container').style.display = 'none';
}
}
document.querySelector('.logout').addEventListener('click', () => {
FB.logout(function() {
setElements(false);
console.log('Logged Out!');
});
});
According to the facebook documentation:
While you can call FB.getLoginStatus any time (for example, when the
user tries to take a social action), most social apps need to know the
user's status as soon as possible after the page loads. In this case,
rather than calling FB.getLoginStatus explicitly, it is possible to
check the user's status by setting status: true when you call FB.init.
To receive the response of this call, you must subscribe to the
auth.statusChange event. The response object passed by this event is
identical to that which would be returned by calling FB.getLoginStatus
explicitly.
https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
It might just be that you're running into a problem with the asynchronous nature of javascript in your code example. Have you checked what your call on getLoginStatus actually returns?
You can take advantage of the browser's localStorage (it' s a method of the window object) to keep the data even after reloading the page or even after closing the window.
Take a look here: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

how do I properly fire this function only if the previous has successfully been completed?

I am attempting to do a series of actions that has a user logout then redirect them to a home page, using parse in Javascript. Here is the logic:
jQuery(document).ready(function() {
$("#logout").on("click", function (e) {
//logout current user
if ( Parse.User.current() ) {
Parse.User.logOut();
// check if really logged out
if (Parse.User.current()) {
console.log("Failed to log out!");
} else {
// redirect page
window.location.replace("home-screen.html");
}
}
});
});
However most times when I logout, back in my parse server, the user session hasn't been destroyed. But I noticed when I remove the window.location action, the user session is destroyed every single time successfully.
So how do I edit my function to say "on click, log user out and ONLY if done successfully THEN redirect page?
Parse.User.logout() returns a promise. Redirect the user after the promise is resolved successfully.
jQuery(document).ready(function() {
$("#logout").on("click", function (e) {
//logout current user
if ( Parse.User.current() ) {
Parse.User.logOut()
.then(function () {
window.location.replace("home-screen.html");
});
}
});
});

Facebook Javascript API keeps reconnecting [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I'm building a site which, when the user connects to Facebook, appends a profile picture to a div, amongst other things. When I leave the site open for a while and come back, I see that the same profile picture has been appended multiple times, so clearly the Facebook connection closes and reopens every so often.
Is there any way to stop this?
Thanks
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '219892158204692',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
// for any authentication related change, such as login, logout or session refresh. This means that
// whenever someone who was previously logged out tries to log in again, the correct case below
// will be handled.
FB.Event.subscribe('auth.authResponseChange', function(response) {
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
fbconnect = true;
$('#fbloginbutton').hide();
$('#friendcontainer').append('<span id="loader"><center>Loading...</center></span>');
// The response object is returned with a status field that lets the app know the current
// login status of the person. In this case, we're handling the situation where they
// have logged in to the app.
FB.api(
"/me",
function (response) {
if (response && !response.error) {
fbid = response['id'];
user['id'] = response['id'];
getuserhighscore(user['id']);
userpercentile(parseInt(user['highscore']));
$('#statscontainer').append('<span class="label">Highest Score</span>: '+user['highscore']+'<br>');
$('#statscontainer').append('<span class="label">Percentile (global)</span>: '+user['percentile']+'<br>');
drawuserchart(user['id']);
}
}
);
FB.api(
"/fql?q=select%20uid%2C%20first_name%2C%20is_app_user%20from%20user%20where%20uid%20in%20(select%20uid2%20from%20friend%20where%20uid1%3Dme())%20and%20is_app_user%3D1",
function (response) {
console.log('friends installed:');
console.log(response);
console.log(response['data'][0].id);
var responseArray = [];
responseArray.push(response);
console.log(responseArray);
user['friends'] = response['data'].length;
if (response && !response.error) {
for (var i=0;i<response['data'].length;i++){
friend = response['data'][i];
console.log('friend coming up');
console.log(friend);
friends.push(friend.uid);
$('#friendcontainer').append('<div class="friendbox" id="'+friend.uid+'"></div>');
$('#'+friend.uid+'').append('<img class="friendpic" src="https://graph.facebook.com/'+friend.uid+'/picture?height=60&width=60&type=square">');
$('#'+friend.uid+'').append('<div class="friendname">'+friend.first_name+'</div>');
gethighscore(friend.uid);
$('#'+friend.uid+'').append(' - '+friendscores[i]+'');
console.log(friendscores);
}
$('#loader').remove();
user['friendrank'] = 1;
for (var i=0;i<friendscores.length;i++){
if(friendscores[i] > user['highscore']){
user['friendrank']++;
}
}
$('#statscontainer').append('<span class="label">Rank (among friends)</span>: '+user['friendrank']+'<br>');
} else {
console.log(response.error)
}
}
);
console.log(friends);
console.log(user)
FB.api(
"/me/picture",
{
"redirect": false,
"height": "100",
"type": "normal",
"width": "100"
},
function (response) {
if (response && !response.error) {
user['picture'] = response['data']['url'];
console.log(user['picture']);
$('#thumbnail').append('<img id="thumbnailpic" src="'+user['picture']+'">');
}
}
);
testAPI();
} else if (response.status === 'not_authorized') {
// In this case, the person is logged into Facebook, but not into the app, so we call
// FB.login() to prompt them to do so.
// In real-life usage, you wouldn't want to immediately prompt someone to login
// like this, for two reasons:
// (1) JavaScript created popup windows are blocked by most browsers unless they
// result from direct interaction from people using the app (such as a mouse click)
// (2) it is a bad experience to be continually prompted to login upon page load.
FB.login();
} else {
// In this case, the person is not logged into Facebook, so we call the login()
// function to prompt them to do so. Note that at this stage there is no indication
// of whether they are logged into the app. If they aren't then they'll see the Login
// dialog right after they log in to Facebook.
// The same caveats as above apply to the FB.login() call here.
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));
// Here we run a very simple test of the Graph API after login is successful.
// This testAPI() function is only called in those cases.
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
$('#sidebar').slideDown("slow");
});
}
</script>
FB.Event.subscribe on auth.authResponseChange is triggered whenever there's change in the auth. A user session is maintained for some minutes, so what's happening is the event is triggered after sometime and the photos are appended again.
You should not write this whole code in this event block.
So, if you want to do this all in this same page, what you can do is, maintain a bool, say bool isLoaded=false;, now when your call is completed: isLoaded=true; indicating that the data is loaded.
And make your API calls whenever it is false, just like this-
if (response.status === 'connected') {
if(isLoaded){
fbconnect = true;
....
....
}
else
// dont do anything
}
Hope that helps!

FB.login not calling callback if cancel is selected

I'm trying to get the users permission if they haven't granted the publish_stream permission.
I have this function:
function AskPermission()
{
ResizeUnity(0);
FB.login(function(response)
{
alert("Hit");
if (response.authResponse)
{
alert('Granted!');
GetUnity().SendMessage("POST", "POST", "Granted");
}
else
{
alert('User cancelled login or did not fully authorize.');
GetUnity().SendMessage("POST", "POST", "");
}
ResizeUnity(1);
}, {scope: 'publish_stream'});
}
When it's called a small window pops up asking .... would like to access your public profile and friends list. There's 2 buttons Okay and cancel. When Okay is pressed it goes on to another screen asking .... would like to post to your friends on your behalf. Again 2 button, Okay and Skip.
When I press the first skip denying all permissions it doesn't return anything. the alert("Hit"); is not called.
When I do press Okay on the first prompt it goes on to the second popup and asks about the posting on behalf. I press Okay, the alert 'Granted' is called.
When I press skip the alert 'Granted' is also called even though I hit skip.
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;
} 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.
}
});
Use this Facebook function to check whether user grant permissions or not.
You can recall same function if user not permitted your app. For more assistance in code, I can help you. :)
For more information see :Fb.getLoginStatus
Maybe this is happening because you are trying to open Facebook login in a popup but it opens in the same window where you called fb.login. When you click Cancel, Facebook tries to close the window, but as it wasn't opened by facebook the window won't close. It never tries to follow the callback url.
Try using in the config {display: "touch"} or {display: "page"} like this:
function AskPermission()
{ResizeUnity(0);
FB.login(function(response)
{
alert("Hit");
if (response.authResponse)
{
alert('Granted!');
GetUnity().SendMessage("POST", "POST", "Granted");
}
else
{
alert('User cancelled login or did not fully authorize.');
GetUnity().SendMessage("POST", "POST", "");
}
ResizeUnity(1);
}, {scope: 'publish_stream', display: 'page'});
}
Is there a reason why not to ask for all the permissions to need in one screen itself. Howevern, keep in mind that as per facebook documentation, ask few permissions to begin with and then keep increasing the permissions request on the go.
https://developers.facebook.com/docs/reference/login/#permissions
Try this code
FB.login(function(response) {
if (response.authResponse) {
var access_token = FB.getAuthResponse()['accessToken'];
console.log('Access Token = '+ access_token);
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: ''});
Hope that helps

Facebook login event subscribe doesn't work

In my web platform I show a Facebook likebox to users.
I need to know when a user log in on Facebook after clicking the like button of the likebox.
I tried to do so by using the FB.Event.subscribe function on events auth.statusChange and auth.authResponseChange (suggested in documentation), but without success.
This is an example of the code I use:
/* Just to wait facebook functions are ready */
var handle = setInterval(function() {
if(typeof(FB) != 'undefined'){
fbReady();
clearInterval(handle);
}
}, 1000);
/* Get connection status */
function fbReady() {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
status == "connected";
} else if (response.status === 'not_authorized') {
status == "not_authorized";
} else {
status == "unknown";
}
/* I don't use status yet */
setSubscriptions(status);
});
}
/* set event listeners for login and liked */
function setSubscriptions(status){
/* Like event subscription */
FB.Event.subscribe('edge.create',
function(response) {
alert('user liked the page');
});
/* status change event subscription */
FB.Event.subscribe('auth.statusChange',
function(response) {
alert('user status is changed in:' + response.status);
});
/* auth response change event subscription */
FB.Event.subscribe('auth.authResponseChange',
function(response) {
alert('user auth response is changed in:' + response.status);
});
}
Only edge.create event fires the related callback when the like button is pressed, but nothing happen when a user log in.
The situation does not change if the user which log in has status connected (he accepted my App in facebook settings) or not_authorized.
I tried to supply a JsFiddle with an interactive code but Facebook js sdk doesn't work that way.
Thanks in advance for your help

Categories