Unable to retrieve the email addresses of Facebook users using the Facebook JavaScript SDK

Utilizing the Facebook authentication feature on my website through javascript sdk, I am able to retrieve my own email and name. However, when users log in, only their names are accessible (since it's linked to my fb developer app).

Despite prompting for login, nothing occurs if no one is currently logged into Facebook. Strangely, inserting an alert at the login section shows the name but not the email. Surprisingly, when testing with my own account, both email and name are successfully retrieved. Why does this discrepancy exist?

Below is a snippet of my code:

<%-- Facebook connection 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>

The intended process is to login, then upon receiving the data, execute the ajax function to access a C# code behind function that redirects users to either the index page if they have an existing account or the registry page if not. The issue lies in the fact that the email parameter remains undefined, preventing entry into the Ajax function. However, the function executes successfully when both email and name are present.

What steps can be taken to properly retrieve the user's email?

Answer №1

After some trial and error, I have figured out the solution. When using the FB.Login function, it is important to include the scope parameter and ensure that the user grants permission. In my specific code, this adjustment looks like:

  FB.login(checkLoginStatus,{scope: 'email'});;

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

Deleting a recently added element using Ajax and MVC3 from both the client-side and server-side

I have a view where I input data into a table called "Students" from the Database. Along with adding students, I also have the functionality to assign books to them using Ajax. Example: Name of Student: ... Books : <dropdown list from database ...

Having trouble removing objects in angular.js?

I have developed an API to be used with Angular.js: angular.module('api', ['ngResource']) .factory('Server', function ($resource) { return $resource('http://localhost\\:3000/api/servers/:name') ...

Swiping carousel feature for mobile devices

My goal is to add carousel swipe functionality for touch devices using only JS/jQuery, without relying on any other libraries. I've created a function for this purpose: $(".carousel-inner").on("touchstart", function(event){ var xClick = event ...

What steps can be taken to modify this jQuery code so that any changes made are also saved to localStorage

I have successfully used jQuery to change the background color of all my divs with the same class (userNumber1) when I check its checkbox. However, I am now looking for a way to save these changes to localStorage, so that they persist each time the page is ...

Utilize AngularJS to bind keys to arrays

Hey there, I have an array that looks like this: $scope.Selectedgroups =[183,184,24] I want to convert it to the format shown below: [{groupId:183},{groupId:184},{groupId:24}]; I've been trying to convert it using a for loop: var groups=[] ...

Retrieve the values of the checkboxes that have been selected using jQuery and pass them to another page for

I am seeking assistance with jQuery as I am a beginner in coding with it. Any solutions or guidance would be greatly appreciated. Here is the markup code I have: <input type='checkbox' data-headmark=".$row['HEAD_MARK']." data-id=". ...

Deactivate the form outside of normal business hours

I need to create a form for a delivery service that only operates from 9am to 9pm. If a user submits the form outside of these hours, I want to redirect them to a page displaying the company's operating hours instead of a thank you page. For instance ...

switching back and forth between the registration and login forms

<script> $(document).ready(function(){ $("#register_link").click(function() { $("#login_or_register").empty(); $("#login_or_register").load("register_form.php"); }); $("#login_link").click(function() { $("# ...

Is there a way to utilize JavaScript to dynamically conceal elements on a webpage?

if (fbValue.job_requested) { var driver_id = fbValue.driver_id; var driver_name = fbValue.driver_name; var requested = fbValue.job_requested; var time = "00:00"; var list_id = "list"+driver_id; if (fbValue.j ...

The AJAX POST request is not receiving the JSON data as expected

After creating an HTML form with the following structure: <form id="loginForm" name="loginForm"> <div class="form-group"> <input type="username" class="form-control" id="username" name="username" placeholder="Your username..." > ...

Transform XML2JS by eliminating square brackets around values

Currently, I am utilizing the xml2js node package for parsing an XML feed. Is there a method to avoid having the values enclosed in square brackets? For instance: "reference": ["ABC123"] should appear as "reference": "ABC123" "items": [ { "r ...

Each time I scroll, the object reloads itself

I am currently facing an issue with a 3D fridge model on my website. Despite successfully loading it, I am encountering a problem where the model refreshes every time it is dragged across the screen by the user scrolling. Please refer to the linked video f ...

Angular: Radio button groups are not responding correctly when populated within a loop using ng-repeat

My goal is to populate multiple sets of radio buttons in a loop by combining the group name and index to ensure each set is uniquely grouped. However, I am facing an issue where only the last group in the loop has a checked radio button, while all other gr ...

Display Middleware Functions Attached in Console

I must say I was quite surprised by my inability to find any relevant information on this topic with a quick Google search. It seems like I may not have been digging deep enough. Essentially, I am seeking details about the middleware functions utilized in ...

Tag - A guide on setting the required attribute for a tag

Currently, I am utilizing Jquery Tag it in order to manage tags and save the values in a database. My challenge lies in using jQuery to make the myTags field required, ensuring that at least one tag is added before proceeding with the save operation. This ...

The image fails to load when attempting to retrieve it from a local JSON file

I successfully managed to fetch data dynamically from a local JSON file created in RN. However, when I tried to add images for each profile to be displayed along with the dynamic profile info, the app encountered an error stating that "The component cannot ...

Create a table by incorporating the information from the page along with additional content

I need to extract the data from a list and convert it into a table, add some additional content that I will provide, and then align the table accordingly. While I can easily align elements and already have the list, I am facing difficulty in converting it ...

Using AJAX to send a POST request to a PHP backend server

Is it required to JSON.stringify the POST parameters/request object when making an AJAX POST call to a PHP backend? Can it be sent as a JS object without conversion? How does PHP handle them differently? Are there any recommended best practices for the re ...

The accumulation of MVC 3 Ajax requests is becoming overwhelming

I'm currently working on the following code snippet: $('.defaultLink').click(function () { $.ajaxSetup({ cache: false }); cleardiv(); $('#mainContent').empty() $('#mainContent').load(this. ...

When trying to use selenium.WebDriver, an error pops up: "missing ) after argument list."

Trying to extract content from the ::after element is proving to be a challenge. Despite my attempts, I keep encountering an exception: "OpenQA.Selenium.WebDriverException: "javascript error: missing ) after argument list My setup includes VSC, Selenium ...