Issue with redirecting after confirming user info permissions on Facebook login

Can anyone assist me with the final step of my Facebook login feature?

The current issue is that when a new user first signs in, they are greeted with a popup labeled 'www.facebook.com/v11.0/dialog/oauth' that asks them to authorize my page to access their information.

The problem arises when the user accepts the terms and clicks on 'continue as name' button, instead of being directed to my homepage as intended, they remain on the login page. They then have to click on the 'Connect by Facebook' button again, which finally redirects them to the correct page.

Basically, I am seeking a solution to streamline the process by prompting the redirect within the oauth popup and avoiding the need for a second click.

My JavaScript code is set up like this:

    $(document).ready(function(){
      $('.login-main').on("click", ".facebook_login_class", function(){
          console.log('FACEBOOK LOGIN OPTION SELECTED');
                FB.getLoginStatus(function(res){
                    if(res.status == "connected" ){
                        console.log('Connected on Facebook');
                        FB.api('/me?fields=email,name,first_name,last_name', function(fbUser) {
                            $.ajax({
                                url:'facebook_login_ajax/',
                                method:'GET',
                                data:{
                                    email:fbUser.email,
                                    code:fbUser.id,
                                },
                                success:function(response){
                                    if (response.Success == true){
                                        window.location.href = '/myhomepage/';
                                    }
                                }
                            });
                        });
                    }else{
                        console.log('NOT CONNECTED!');
                        FB.login();
                    }
                    FB.getLoginStatus(function(response) {
                    });
                });

            });
      });

I believe the issue lies within the FB.login(); section of my code, as that is where new users are taken before providing authorization. My JavaScript skills are still improving, so it feels like I may be overlooking something simple.

Do any of you have a suggestion for resolving this issue?

Thank you very much

Answer №1

Well, it turns out that the solution was right in front of me all along. All I had to do was tweak the FB.login(); section like so:

                    FB.login(function(response) {
                       if (response.status == 'connected'){
                        FB.api('/me?fields=email,name,first_name,last_name', function(fbUser) {
                        $.ajax({
                            url:'facebook_login_ajax/',
                            method:'GET',
                            data:{
                                email:fbUser.email,
                                code:fbUser.id,
                            },
                            success:function(response){
                                if (response.Success == true){
                                    window.location.href = '/myhomepage/';
                                }
                            }
                        });
                    });
                       }
                    }, {scope: 'email'});
                }

Basically, it's the same function as before, but now it's nested under the FB.login() function.

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

Displaying a DIV after entering text into an <input> field using JavaScript

Attempting to create a JavaScript function that will show/hide a 'DIV' after entering some text into an input field. I have successfully written the function, but I am struggling to make it only work when the user enters a value greater than 8. ...

Maximizing for-loop efficiency: the advantage of caching array length

Let's compare two variations of a loop iteration: for (var i = 0; i < nodes.length; i++) { ... } and var len = nodes.length; for (var i = 0; i < len; i++) { ... } Would the second version be faster than the first one in any way? ...

Can someone explain the significance of receiving a TypeError when trying to access properties of null (specifically 'useRef') in a React application?

I encountered an issue while working on a React project...the browser console displays the following error. What does this mean? And how can I resolve it? react.development.js:1545 Uncaught TypeError: Cannot read properties of null (reading 'useRef ...

Bump the version number and request a message for the commit

Recently diving into the world of Grunt, I've been experimenting with merging grunt-bump and grunt-prompt. My intention is to have users prompted for a commit message that will then be added to the commit. I looked to this article for guidance in str ...

What is the process for obtaining a value when you click and then retrieving the associated ID?

I am looking to create a function that, when clicking on the square with the ID "colors", will return the sentence containing the colors from the table in PHP files with the ID "retours_couleurs". Apologies for any mistakes in my English, as I am French. ...

Enhancing XTemplate in ExtJS 4.2.1 with dynamic data refresh from store

Here's a situation that's quite unique... A DataView linked to a store is causing me some trouble. In the XTemplate, I want to display the quantity of a specific type of JSON record. Each record has a 'type' property with a value. For ...

Using regular expressions, you can eliminate a specific segment of a string and substitute

Provide a string in the following format: lastname/firstname/_/country/postalCode/_/regionId/city/addressFirst/addressSecond/_/phone I am creating a function that will extract the specified address parts and remove any extra parts while maintaining maxim ...

The requested API endpoint is correct, but the response returned is indicating that it was

I've set up a Django Rest Framework Endpoint for handling user settings: urlpatterns_usersettings = [ path("usersettings/<int:pk>/", UpdateUserSettings.as_view()) ] Next, let's take a look at the view responsible for managing this endp ...

Is it possible to streamline multiple $.fn. calls using javascript or jQuery?

I recently started using datatables and was advised to include the following code: $.fn.dataTableExt.oStdClasses.sWrapper = 'no-margin last-child'; $.fn.dataTableExt.oStdClasses.sInfo = 'message no-margin'; $.fn.dataTableExt.oStdClasse ...

Create a duplicate array with all distinct elements - JavaScript

Help needed: I am facing an issue with an array of objects. My goal is to create a unique copy of this array to prevent any changes in the original one when modifications are made to the new array. I have experimented with several methods, including: let ...

Best method for retrieving information from a string

Exploring different techniques to extract data from a string is a common practice, including methods like substring and split. Is there an optimal approach to accomplish this task? For instance, when faced with a URL structure such as http://myServer:8000/ ...

The outcome of the AJAX RSS Reader remains unpredictable

Utilizing the AJAX RSS Reader (visit this link) for extracting RSS data from my URL: http://vtv.vn/trong-nuoc.rss In my php file (readRSS.php): <?php $url = ("http://vtv.vn/trong-nuoc.rss"); $xmlDoc = new DOMDocument(); $xmlDoc->load($url); $ ...

Making If Statements Easier

Currently, I'm tackling an assignment that involves utilizing if statements and switch statements. Here is a snippet of code that I am working on: if (validateField(document.forms[0].name) == false) { isValid = false; } if (validateField(docume ...

What is the best way to access and verify data from an array that has been passed through props

I am working with a component that takes an array as a prop <Component runners={['1','2']}/> Inside this functional component, my goal is to generate an element for each value in the array. Here's my logic: const { runners ...

Stop options from being hidden in a select dropdown using HTML

Can I keep the options visible when a user selects an item in the 'select' dropdown? I want to add more options to the 'select' when the user clicks on the 'op2' item, without closing the list of options. <select> <o ...

Prevent Xdebug from processing multiple requests

One recurring issue I encounter in my app is calling an API endpoint every 60 seconds. However, when I attempt to debug using Xdebug, stepping through the controller associated with that endpoint often takes longer than a minute. This results in another re ...

What is the alternative method in JavaScript for locating items instead of using indexOf?

I have a set of paths in an array. Some paths are classified as constants while others are labeled as dynamic. A constant path would be something like "/booking-success", whereas a dynamic path could be something like '/arrival/view/:job_or ...

JavaScript error message stating that the setAttribute function is null

As a newcomer to JS, I am currently working on creating a task list webpage that allows users to submit projects and create task lists within each project with designated due dates. In order to generate unique ID tags for projects and tasks, I utilized UU ...

Merge array and object destructuring techniques

What is the correct way to remove a value from an array? const ?? = { text: ['some text'] }; ...

What is the best way to test speedy AJAX response times using Webdriver.io?

Currently, I am creating Cucumber.js tests using Webdriver.io. Everything seems to be going smoothly, but I'm encountering an issue with the mock server responding too quickly with AJAX. The "Loading..." message is not visible because the content load ...