Tuesday, 9 August 2022

Wordpress Login Form - How to show error message without reload page

I'm building my own custom login page for wordress. The login form seems to work, however I would like to be able to customize the error message more specifically.

When the login credentials are incorrect and you log in, the error message appears only after the page has reloaded. What I would like to do is show the error message without reloading the page.

I searched on stackoverflow and wordpress reference but couldn't find a solution for my case. Anyone have a suggestion on how I might achieve my goal?

Thanks for any replies, I appreciate any help.

Update 2

I thank the users who helped me with their answers, they were very helpful and I really appreciate it. I literally spent all day on this problem, I finally achieved my goal. The ajax request works and the message is displayed as I wanted. I had to go through a lot of things several times. However I leave the updated code for anyone who needs help.

My custom_login_page.php file
This contains the html structure, the form and the script that executes the ajax requests. Put the file in your active child theme. In my case I called the custom_login_page.php file. For this to be read by wordpress you need to create a new page and select it as a template.

enter image description here

<?php

// Template Name: Custom Login Page

?>

<?php get_header(); ?>

  <div class="container_main">
    <?php if (is_user_logged_in()) { 
      ?><span>Sei gia loggato</span><?php // If the user is logged in, it shows the message below
    } else { // otherwise, if the user is not logged in, it shows the login form
      ?>
        <form id="login" action="login" method="post">
          <!-- Message error --> 
          <p class="status"></p> 
          
          <!-- Username --> 
          <label for="username">Username</label>
          <input id="username" type="text" name="username">

          <!-- Password -->
          <label for="password">Password</label>
          <input id="password" type="password" name="password">

          <!-- Link Recover -->
          <a class="lost" href="<?php echo wp_lostpassword_url(); ?>">Lost your password?</a>

          <!-- Submit Button -->
          <input class="submit_button" type="submit" value="Login" name="submit">
          
          <?php wp_nonce_field( 'ajax-login-nonce', 'security' ); ?>
        </form>
      <?php
    } ?>
  </div> 

<?php get_footer(); ?>

<script>
jQuery(document).ready(function($) {
  // Perform AJAX login on form submit
  $('form#login').on('submit', function(e){
      $('form#login p.status').show().text(ajax_login_object.loadingmessage);
      $.ajax({
          type: 'POST',
          dataType: 'json',
          url: ajax_login_object.ajaxurl,
          data: { 
              'action': 'ajaxlogin', //calls wp_ajax_nopriv_ajaxlogin
              'username': $('form#login #username').val(), 
              'password': $('form#login #password').val(), 
              'security': $('form#login #security').val() },
          success: function(data){
              $('form#login p.status').text(data.message);
              if (data.loggedin == true){
                  document.location.href = ajax_login_object.redirecturl;
              }
          }
      });
      e.preventDefault();
  });
});
</script>

My functions.php file
In functions.php I put the functions linked to the form and some redirects useful when doing logine logout.

/* Redirect Custom Login Page */
function redirect_custom_login_page() {
  wp_redirect(site_url() . "/login");
  exit();
}
add_action("wp_logout", "redirect_custom_login_page");


/* Redirect wp-admin & wp-login php */
add_action("init","fn_redirect_wp_admin");
function fn_redirect_wp_admin(){
    global $pagenow;
    if($pagenow=="wp-login.php" && $_GET['action'] !="logout"){
        wp_redirect(site_url()."/login");
        exit();
    }
}

/* Ajax Form Login */
function ajax_login_init(){

    wp_register_script('ajax-login-script', get_template_directory_uri() . '/ajax-login-script.js', array('jquery') ); 
    wp_enqueue_script('ajax-login-script');

    wp_localize_script( 'ajax-login-script', 'ajax_login_object', array( 
         'ajaxurl' => admin_url( 'admin-ajax.php' ),
         'redirecturl' => home_url(),
         'loadingmessage' => __('Sending user info, please wait...')
    ));

    // Enable the user with no privileges to run ajax_login() in AJAX
    add_action( 'wp_ajax_nopriv_ajaxlogin', 'ajax_login' );
}

// Execute the action only if the user isn't logged in
if (!is_user_logged_in()) {
    add_action('init', 'ajax_login_init');
}

function ajax_login(){

    // First check the nonce, if it fails the function will break
    check_ajax_referer( 'ajax-login-nonce', 'security' );

    // Nonce is checked, get the POST data and sign user on
    $info = array();
    $info['user_login'] = $_POST['username'];
    $info['user_password'] = $_POST['password'];
    $info['remember'] = true;

    $user_signon = wp_signon( $info, false );
    if ( is_wp_error($user_signon) ){
        echo json_encode(array('loggedin'=>false, 'message'=>__('Wrong username or password.')));
    } else {
        echo json_encode(array('loggedin'=>true, 'message'=>__('Login successful, redirecting...')));
    }

    die();
}


from Wordpress Login Form - How to show error message without reload page

No comments:

Post a Comment