Jordan Lewallen
Jordan Lewallen

Reputation: 1851

Ajax user registration failing upon submission issue

I am trying to implement an ajax modal signup form where users can register for the site. I have managed to get the login form working, but I am hitting a snag on registration. I took my login modal template as reference. Where did I go wrong?

UPDATE I've managed to get the database to register the user..and I've updated the code below. Few things now.

  1. The page doesnt redirect to homepage upon registration
  2. It doesnt have the user logged in when I do refresh the page
  3. Checking phpMyAdmin, the password the user inputs is not what is found in the database (a random string of text is there)
  4. When I use this random string of text OR the password that they registered with, the login fails.

My HTML.

<div id="signup-body" class="toggleMe">
                    <form class="form" id="signupform" role="form" name="signupform" action="" method="post">
                        <p class="status"></p> <!-- testing the status -->
                        <div class="form-group">
                            <label class="sr-only" for="signup-name">Username</label>
                            <input type="text" class="form-control" id="signupname" name="signup-name" placeholder="Username">
                        </div>
                        <!-- Form Group -->
                        <div class="form-group">
                            <label class="sr-only" for="signup-email">Email</label>
                            <input type="email" class="form-control" id="signupemail" name="signup-email" placeholder="Email">
                        </div>
                        <div class="form-group">
                            <label class="sr-only" for="signup-password">Password</label>
                            <input type="password" class="form-control" id="signuppassword" name="signup-password" placeholder="Password">
                        </div>
                        <!-- Form Group -->

                        <input type="submit" class="btn btn-secondary signup-modal-button" value="Sign Up">
                        <?php wp_nonce_field( 'ajax-login-nonce', 'security' ); ?>
                    </form>
                </div>

JQuery Code

jQuery(document).ready(function($) {

    // Perform AJAX login on form submit
    $('form#signupform').on('submit', function(e){
        $('form#signup p.status').show().text('Sending user info, please wait...');
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: "<?php echo admin_url( 'admin-ajax.php' );?>",
            data: {
                action: 'register_user', //calls wp_ajax_nopriv_ajaxlogin
                'username': $('form#signupform #signupname').val(),
                                'email': $('form#signupform #signupemail').val(),
                'password': $('form#signupform #signuppassword').val(),
                'security': $('form#signupform #security').val() },

            success: function(data){
                    console.log(data);
                $('form#signup p.status').text(data.message);
                if (data.loggedin == true){
                    document.location.href = ajax_login_object.redirecturl;
                }
            },error: function (data) {
                console.log(data);
            }

        });
        e.preventDefault();
    });

});

In the functions.php

function ajax_signup_init(){

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

wp_localize_script( 'ajax-signup-script', 'ajax_signup_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('init', 'ajax_signup_init');

function ajax_signup(){

    // 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_email'] = $_POST['email'];
    $info['user_password'] = $_POST['password'];
    $info['remember'] = true;


    $user_signup = wp_insert_user( $info);

    if (!is_wp_error($user_signup) ){
         echo "User created : ". $user_signup;
    }

    die();
}

add_action( 'wp_ajax_register_user', 'ajax_signup' );
add_action( 'wp_ajax_nopriv_register_user', 'ajax_signup' );

Upvotes: 0

Views: 555

Answers (2)

Vel
Vel

Reputation: 9341

Your ajax callback function should be like below.

        function ajax_signup(){

            // 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_email'] = $_POST['email'];
            $info['user_password'] = $_POST['password'];
            $info['remember'] = true;


            $user_signup = wp_insert_user( $info);  

            if (!is_wp_error($user_signup) ){
                echo json_encode(array('loggedin'=>true, 'message'=>__('Sign up successful, redirecting...')));
            } else {
                echo json_encode(array('loggedin'=>false, 'message'=>__('Wrong username or password.')));
            }
            wp_set_current_user($user_signup);
            wp_set_auth_cookie($user_signup);
            die();
        }

        add_action( 'wp_ajax_ajax_login', 'ajax_login' );
        add_action( 'wp_ajax_nopriv_ajax_login', 'ajax_login' );

You have to add these two in your code.

   wp_set_current_user($user_signup);
   wp_set_auth_cookie($user_signup);

Upvotes: 1

Fabiano Araujo
Fabiano Araujo

Reputation: 932

First you don't need to use the full path of a element with id attribute with jQuery, doing so makes it harder and uses more resources. You can use:

data: {
    action: 'register_user', //calls wp_ajax_nopriv_ajaxlogin
    'username': $('#signupname').val(),
    'email': $('#signupemail').val(),
    'password': $('#signuppassword').val(),
    'security': $('#security').val() 
},

And if you do have more elements with the same id, stop what you doing and read about the id attribute.

Next, in your success callback you use the value data.loggedin although you never echoed a valid JSON output on ajax_signup function. That's probably why there is no redirect.

For why the data is not being written correctly to database, use a var_dump($_POST) and check for the response on Developer Tools' network tab. You may want to open this before the request to make sure it's captured.

Last, I may be wrong since I don't use Wordpress for a long time, but since you used only wp_insert_user, there is no way you return a user logged, or at least it's not documented: https://developer.wordpress.org/reference/functions/wp_insert_user/

Upvotes: 0

Related Questions