skip to Main Content

I’m building my wordpress login page, everything is working fine. So I decided to implement facebook social login using their SDK. Social login works fine and login successfully.

The problem is that after login the user should be directed to the homepage of the website "www.mywebsite.com". I tried to manage the redirect with javascript code, but after successful login no redirection happens.

Can anyone help me figure out what I’m doing wrong?

This is the part where I’m trying to create the redirect

jQuery.post(ajaxurl, data, function(response) {
                            if (response.success) {
                                wp_safe_redirect( '/' );
                                exit;
                            } else {
                                document.getElementById('login-form-message').innerHTML = response.message;
                            }
                        });

This is the complete code that concerns the social login of facebook

/* Manage Social Login Script */
    window.fbAsyncInit = function() {
    FB.init({
      appId      : 'xxxxxxxxxxxxxxx',
      cookie     : true,
      xfbml      : true,
      version    : 'v15.0'
    });
        
        var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
        document.getElementById('facebook-login-button').addEventListener('click', function() {
            FB.login(function(response) {
                if (response.authResponse) {
                    FB.api('/me', {fields: 'name,email'}, function(response) {
                        var data = {
                            'action': 'facebook_login',
                            'facebook_id': response.id,
                            'access_token': FB.getAuthResponse().accessToken,
                            'email': response.email,
                            'username': response.name
                        };
                        jQuery.post(ajaxurl, data, function(response) {
                            if (response.success) {
                                wp_safe_redirect( '/' );
                                exit;
                            } else {
                                document.getElementById('login-form-message').innerHTML = response.message;
                            }
                        });
                    });
                } else { 
                    document.getElementById('login-form-message').innerHTML = 'User cancelled login or did not fully authorize.';
                }
            }, {scope: 'email'});
        });
    }

    (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'));

This is the PHP code that handles the ajax request

//** Facebook Login AJAX Handler **/ 
function facebook_login_handler() {
   // Verify ID token
   $facebook_id = $_POST['facebook_id'];
   $access_token = $_POST['access_token'];
   $email = $_POST['email'];
   $username = $_POST['username'];
   $response = wp_remote_get( 'https://graph.facebook.com/v3.3/' . $facebook_id . '?access_token=' . $access_token );
   $facebook_response = json_decode( wp_remote_retrieve_body( $response ), true );

   if ( ! isset( $facebook_response['id'] ) ) {
       $response = array(
           'success' => false,
           'message' => 'Invalid Facebook ID token'
       );
       echo json_encode( $response );
       wp_die();
   }

   // Check if the user already exists in our database
   $user = get_user_by( 'email', $email );
   if ( ! $user ) {
       $user = get_user_by( 'login', $username );
   }

   if ( $user ) {
       // Update user meta with Facebook ID
       update_user_meta( $user->ID, 'facebook_id', $facebook_id );
       // Log the user in
       wp_set_current_user( $user->ID );
       wp_set_auth_cookie( $user->ID );
       $response = array(
           'success' => true,
           'message' => 'Login successful'
       );
   } else {
       // If the user does not exist, create a new account
       $user_data = array(
         'user_login' => $username,
         'user_email' => $email,
         'user_pass' => wp_generate_password()
     );
     $user_id = wp_insert_user( $user_data );
     if ( is_wp_error( $user_id ) ) {
         $response = array(
             'success' => false,
             'message' => $user_id->get_error_message()
         );
         echo json_encode( $response );
         wp_die();
     } else {
         update_user_meta( $user_id, 'facebook_id', $facebook_id );
         wp_set_current_user( $user_id );
         wp_set_auth_cookie( $user_id );
         $response = array(
             'success' => true,
             'message' => 'Registration and login successful'
         );
     }
 }
 echo json_encode( $response );

 wp_die();
}

2

Answers


  1. Chosen as BEST ANSWER

    After several hours of searching I figured out that the problem lay in: jQuery.post(ajaxurl, data, function(response). So I changed the code as follows and the redirect is working fine.

    From this

    jQuery.post(ajaxurl, data, function(response) {
                                if (response.success) {
                                    location.href = '<?php echo home_url(); ?>';
                                } else {
                                    document.getElementById('login-form-message').innerHTML = response.message;
                                }
                                });
    

    To this

    // Invia la richiesta ajax al server per elaborarla
                      $.ajax({
                         type: 'POST',
                         url: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
                         data: data,
                         success: function(response) {
                            console.log(response);
                            if (response.success) {
                               // reindirizzamento alla pagina home
                               window.location.href = '/';
                            } else {
                               // reindirizzamento alla pagina di login
                               window.location.href = '/experimental-layout';
                            }
                         }
                      });
    

  2. Man, wp_safe_redirect() – this is wordpress function, not javascript…

    Use location.href = 'Your Url'

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search