Endless Cycle of Facebook Login

I'm encountering an issue with the Facebook Login feature on my website. At first, I tried using only FB.Login but received the message: "FB.login() called when user is already connected."

So, I added FB.getLoginStatus to address this problem. However, now it seems to continuously log me in, creating an infinite loop even when I am already logged into my system and haven't clicked the FB-Connect Button.

How can I prevent it from automatically logging me in until I actually click the FB-connect Button?

<div id="fb-root"></div>
<script>(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/fb_LT/all.js#xfbml=1&appId=198866780209581";
     fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

window.fbAsyncInit = function() {
      FB.init({
         appId      : "198866780209581", // 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;
      $.ajax({
              type: "POST",
              url: "/?eID=login&modus=facebook&fb-login=1",
              data: $(this).serialize(),
              success: function(msg) {
              console.log("LOGIN");
              window.location.reload();
              }
            })
      var uid = response.authResponse.userID;
      var accessToken = response.authResponse.accessToken;
    }
    else{
      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 + '.');
         if(login===false)
         {
           alert('not connected');
         }
       });
       } else {
       console.log('User cancelled login or did not fully authorize.');
       }   
     }, {scope: 'email'});
    }});
// Additional initialization code here
};

</script>

Answer №1

The solution involved updating the click function as follows:

$(".fb-login-button").on("click", function() {

}

After making this change, my final code now appears like this:

<div id="fb-root"></div>
<script>(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/fb_LT/all.js#xfbml=1&appId=198866780209581";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
window.fbAsyncInit = function() {
    FB.init({
      appId      : "198866780209581", 
      status     : true,
      cookie     : true,
      xfbml      : true,
      oauth      : true,
    });   
    var login = false;
  $(".fb-login-button").on("click", function() {
FB.getLoginStatus(function(response) {
 alert('hier 1');
    if (response.status === 'connected') {
 alert('connected');
      console.log('connected');
      login=true;
      $.ajax({
              type: "POST",
              url: "/?eID=login&modus=facebook&fb-login=1",
              data: $(this).serialize(),
              success: function(msg) {
              console.log("LOGIN");
              window.location.reload();
              }
            })
      var uid = response.authResponse.userID;
      var accessToken = response.authResponse.accessToken;
    }
    else{
      alert('im else');
      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 + '.');
         if(login===false)
         {
           alert('nicht connected');
         }
       });
       } else {
       console.log('User cancelled login or did not fully authorize.');
       }   
     }, {scope: 'email'});
    }});
});
// Additional initialization code here
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS controller function fails to trigger

I have three directives, "parenta", "parentb", and "childb". The first two are siblings while the third one is a direct child of "parentb". When attempting to call a controller method from "parenta", it does not work. Strangely, calling a method on the "c ...

Fetch additional information via Ajax request when button is clicked within MVC 4

I am building a feature to display 6 records in an HTML table with a button labeled Load More. The goal is for each click of the button to retrieve another set of 6 records. Here's what I have tried so far: Within the Controller [HttpGet] private Js ...

establishing a minimum number of characters in a regular expression enclosed in parentheses

/^[a-z]+[0-9]*$/igm Tom //valid tom12123 //valid 12tom //invalid to12m //invalid T23 //valid T //valid but I want a minimum of two characters. /^([a-z]+[0-9]*){2,}$/igm Tom //valid tom12123 //valid 12tom //invalid to12m //should be inval ...

The functionality of a JQuery post within a PHP loop is not functioning optimally

I am encountering an issue with my list.php file, which generates a list with items and a button (Erledigt!) that triggers a jQuery Post to wishdelete2.php. The problem is that the jQuery post sometimes requires multiple clicks (3x or 5x) before it process ...

Remove all spaces from input fields in angular Typescript, excluding the enter key

I've encountered an issue where the code below removes all spaces, but it's also removing the enter key. Is there a way to remove only spaces and not affect the enter key? static stripDoubleSpaces(str: string): string { if (!!str) { ...

Using Vue.js to dynamically append varying inputs upon user interaction

When I select an option, I want to display different types of inputs based on the selected option. For Example: Select input -> show input fields Select textarea -> show text areas Select boolean -> show radio buttons The Code This is where ...

Having trouble deciding between flatMap and concatMap in rxJs?

Having trouble grasping the distinction between flatMap and concatMap in rxJs. The most enlightening explanation I found was on this Stack Overflow post about the difference between concatMap and flatMap So, I decided to experiment with it myself. import ...

Learn how to incorporate an image into your Codepen project using Dropbox and Javascript, along with a step-by-step guide on having the picture's name announced when shown on the screen

Hey there, I'm in need of some assistance. I have a Codepen page where I am working on displaying 4 random shapes (Square, Triangle, Circle, and Cross) one at a time, with the computer speaking the name of each shape when clicked. I want to pull these ...

concealed highcharts data labels

I attempted to create a bar chart using Highcharts, and initially it worked fine. However, I encountered an issue when displaying multiple indicators - the datalabels for certain data points are hidden. For example, the datalabel for "provinsi aceh" is not ...

Inaccessible " following the "Return" Conflict

I'm struggling to resolve these warnings: Merge this with the previous "var" statement, found on lines 7, 9 and 10. Unreachable " after 'Return' - it's related to ($window.width() <= 770) { return; Script snippet: //StickyB ...

Using JavaScript in Django templates: Displaying errors with a JavaScript function

Update: I recently made changes to my code, and it now looks like this: <script> function updateFunction(calibrationId) { document.getElementById(calibrationId).innerHTML = "<ul><li>" + calibrationId + "</li>" ...

Clearing cookies in Express.js can be a challenging task

I've tried multiple options, but I can't seem to delete the cookie. Can anyone help me understand this? I have attempted using set maxage, expires, setheaders, but nothing seems to delete the cookie. It's impossible. res.cookie("refres ...

Tips for properly panning across the canvas

I added event listeners to capture mouse movement, clicks, and releases in my code. canvas.addEventListener('mousemove', onMouseMove, false); canvas.addEventListener('mousedown', onMouseDown,false); canvas.addEventListener('mouseu ...

What is the best way to search for all results in MongoDB that have x appearing in any property?

Is it possible to search for all pictures in the mongoose framework with node and express that contain a specific parameter, regardless of which property holds that parameter? For example: If I enter "John Snow" in the search bar, I want to see all pictur ...

Dynamic Dropdown List in Rails with Cascading Selects

I am fairly new to this and have been attempting to make it function. My goal is to dynamically populate the Rooms select on my form using Ajax once the Location has been chosen (on_change). I tried to follow this guide - - but I'm facing difficult ...

Is there a way to send the image object to the onclick function as it is being assigned?

I apologize if my question is a bit unclear, as I am currently teaching myself how to use javascript. I am working on generating image thumbnails dynamically and would like the ability for users to enlarge the image when they click on the thumbnails. The p ...

The functionality of the Jquery expand and collapse menu appears to be malfunctioning

I'm currently working on implementing a sidebar menu navigation that expands and collapses when the user clicks on the menu. Additionally, I want the menu to remain expanded if a link in the sub-menu is active when the page loads. Below is the code s ...

Tips for adjusting the color of multiple classes that have a common class using a toggle feature

I am working on a simple website using bootstrap 4 and SCSS. I want to include a toggler that switches between dark and light modes on the webpage. However, I'm facing an issue with changing the background color of 6 Bootstrap cards, footer, and the t ...

Oops, looks like the server is experiencing some technical difficulties. The request is taking too long to process and has timed out

I find myself in a predicament with my shared hosting. Despite modifying my ajax requests to be smaller and adding timeouts after each request, the issue persists. How can I resolve this problem while using shared hosting? Note: set_time_limit(0); is not p ...

Sending Data From Ajax to JavaScript

While I know this question has been asked and answered a few times before, the exact context of my query remains unanswered. To ensure full understanding, I would like to pose my specific scenario. I am looking to trigger a server-side call to query infor ...