The Facebook SDK's function appears to be triggering twice

I am currently in the process of integrating a Facebook login button into my website and have made progress, but I have encountered a problem. The Facebook SDK JavaScript code that I am using is as follows:

  function statusChangeCallback(response) {
    console.log(response);
    if (response.status === 'connected') {
      getUser();
    } else {
      document.getElementById('status').innerHTML = 'Please log ' +
        'into this app.';
      }
  }

  function checkLoginState() {
    FB.getLoginStatus(function(response) {
      statusChangeCallback(response);
    });
  }

  window.fbAsyncInit = function() {
    FB.init({
      appId      : 'XXXXX',
      cookie     : true,
      status     : true,
      xfbml      : true,
      version    : 'v2.8'
    });

    FB.getLoginStatus(function(response) {
      statusChangeCallback(response);
    });
  };

  (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 = "https://connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));

  function getUser() {
    FB.api('/me?fields=email,name,birthday,gender', function(response) { 
      var ufd=JSON.stringify(response);
        $.ajax({
          type: "POST",
          url: "/fb-callback.php",
          data: {ud:ufd},
          success: function(msg) {
            if(msg!=""){
              alert("Successfully Logged In !"+msg);
            }
            else{
              alert("Some Error");
            }
          }
        });  
    });
  }

In the getUser() function, the ajax call seems to be triggered twice or the function itself is being called twice. Despite searching for solutions, I have not found anything relevant to address this particular issue.

Answer №1

If a user is already logged in to your App with Facebook, the function statusChangeCallback(response) will be triggered once inside the window.fbAsyncInit block.

FB.getLoginStatus(function(response) {
  statusChangeCallback(response);
});

When you log in using the Facebook Login button on your page, the function checkLoginState() will call statusChangeCallback(response) again, causing your ajax call to trigger twice. To fix this issue, there are two possible solutions:

  1. Hide the Login button if response.status === 'connected', meaning the user is already logged in automatically.
  2. Remove the FB.getLoginStatus check from the init section and prompt the user to log in to your app by clicking the login button each time they visit your page.

Answer №2

Within the getUser function, there are two functions that trigger ajax requests. The first one is FB.api('/me?fields=email,name,b, and the other one is the callback function.

var ufd=JSON.stringify(response);
        $.ajax({
      type: "POST",

Therefore, it will naturally initiate two separate ajax requests.

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

Unable to generate STYLE element within iframe header

Check out this jsfiddle link: http://jsfiddle.net/uTy5j/7/embedded/result/ I've encountered an issue with CodeMirror where it seems to erase the style tag I create using the following code: var preview = document.getElementById('preview') ...

The navigation in Framework 7 is causing issues with the on-click functionality

Utilizing the framework's built-in formToJSON() function, I have been able to retrieve form values. By utilizing a click event, I am able to log the values. $$("#query-submit").on("click", function () { var queryForm = app.formToJSON("#query-form ...

Unidentified googletagmanager detected in vendors segment

Recently, my ad blocker detected an unfamiliar Google Tag Manager request originating from a chunk provided by one of my vendors. Is it typical for tracking to be embedded in dependencies like this? And what type of information can be collected from my we ...

Calculating every number within a range of dates and storing them in the format of [day, hour]

Given two date pairs represented as numbers [hour, weekday], where hour ranges from 0-23 and weekday ranges from 1-7. I am tasked with generating all the hours in between each pair. For example, if given [13, 2] and [2, 3], the output would be: [13,2] [14 ...

Using regular expressions in JavaScript, eliminate all characters preceding a specified final character

I am attempting to eliminate all text that precedes the last character in a Regex pattern. For example: rom.com/run/login.php Would turn into: login.php Can someone guide me on how to achieve this using JavaScript? I have limited experience with regul ...

Autonomous JQuery Modules

Is it possible to separate the functions in JQuery and use only the ones needed by splitting the file with PHP? By doing this, I aim to improve page speed, save bandwidth, and have more control over the functions used through the backend. Can the functio ...

Steps for importing jQuery typings into TypeScript:1. First, install the jQuery

I've searched for similar questions, but haven't found one that matches my issue. Can someone help me figure out what to do next? In my Visual Studio project, I used package.json to download jquery typings into the node_modules folder: { "ver ...

Update the class name by utilizing template literals

I'm currently in the process of mastering template literals as I have a project where I need to utilize them. However, I seem to be encountering an issue that I can't quite figure out. Here is the code that is currently working: const classes = ...

The AbortController feature does not initiate the cancellation of an axios.get request

Currently, I'm experimenting with utilizing AbortController to cancel an API call. The axios library is being used for this particular call. Before integrating it into my project, I decided to test the cancellation procedure with a simple call: const ...

What is the best way to extract values from this PHP script?

I recently delved into the d3 javascript library and successfully created a scatter plot chart that pulls random values from an array. Below is the code snippet: <!DOCTYPE html> <meta charset="utf-8"> <head> <script type="text/ja ...

Using React.js to Retrieve Data from the Server without AJAX Calls

Currently, I am in the process of creating a web application using Express.js for the back-end and React.js for the front-end. Prior to using React.js, I utilized EJS templating and followed a similar workflow on the back-end as shown below: var express = ...

Tips for implementing validation in AngularJS

Could someone help me with AngularJS validation? I'm new to it and trying to make sure everything is correct. var app=angular.module('myApp',[]) app.controller('myController',function($scope){ $scope.clickMe = function(){ if($(& ...

Error in Node.js: Unhandled promise rejection due to undefined value

We're currently facing an issue with the create user controller in Node.js Express. The problem arises when attempting to sign up on the front end, resulting in an error message: "Unhandled promise rejection error value is not defined." Although it ap ...

Error found when combining a stopwatch with the react useState hook and setInterval, causing an additional interval to start when the stopwatch

I have implemented a stopwatch feature that includes start and pause buttons. The start button triggers setInterval while the pause button calls clearInterval. Initially, pressing start and then pause works correctly. However, if you press start again afte ...

Scrolling animations tailored to the navbar using jQuery

My fixed header contains a few links, and I've written some code that almost works perfectly. The issue is that there's a delay when the second function is executed. While it successfully scrolls to the top of the page when the linked element is ...

How to Use JavaScript Function to Rotate an Entire Webpage

For my final project in a web design class, we were tasked with creating a website that showcases our skills. I've completed the assignment and now I want to add some interesting features to make it stand out. I'm interested in using -webkit-tra ...

Issue encountered in transmitting information from JSP to servlet

I am facing an issue with receiving data from JSP to servlet. I understand that I need to serialize this data using JSON. In my JSP, I have written the following JavaScript code: var myJSONText = JSON.stringify(items); document.getElementById('test&a ...

Incorporating React into an already existing webpage and accessing URL parameters within a .js file

Following the official guidelines: To include React in a website, visit https://reactjs.org/docs/add-react-to-a-website.html I have created a file named test.html with the following content: <!DOCTYPE html> <html> <head> < ...

Creating a basic bar chart using NVD3 with X and Y axes in AngularJS

I'm currently utilizing the nvd3.js plugin within my angular-js application. I have a straightforward task of creating a bar chart, where bars represent months along the x-axis and revenue values on the y-axis. My goal is to accomplish this using the ...

How to Remove Multiple Entries With Checkbox Selection in ASP.NET MVC Without Entity Framework

I am currently working on a project with ASP.NET MVC and I am facing an issue while trying to delete multiple records using checkboxes. Whenever I select a record and click on the Delete button, it is taking the Id as null. Can someone please suggest a sol ...