Show success or error messages in Ajax response to Wordpress custom registration form

3.1k views Asked by At

I have this custom form inside a Wordpress page template

<?php if(!is_user_logged_in()) {
if(get_option('users_can_register')) { 
    if($_POST){
        $username = $wpdb->escape($_REQUEST['user_login']);
        if(empty($username)) {
            echo "<span style='color:#FF0000'><strong>Error..</strong></span><br /><br />You have to fill in the username.";
            exit();
        }
        $email = $wpdb->escape($_REQUEST['user_email']);
        if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/", $email)) {
            echo "<span style='color:#FF0000'><strong>Error..</strong></span><br /><br />please use a calid e-mailadress.";
            exit();
        }

        //$random_password = wp_generate_password( 12, false );
        $pass1 = $wpdb->escape($_REQUEST['pass1']);
        $pass2 = $wpdb->escape($_REQUEST['pass2']);
        if ($pass1 != $pass2){
            echo "<span style='color:#FF0000'><strong>Error..</strong></span><br /><br />please use a passwords don't match.";
                exit();

        }
        $random_password = $pass1;
        $status = wp_create_user( $username, $random_password, $email );
        if ( is_wp_error($status) )
            echo "<span style='color:#FF0000'><strong>Feil..</strong></span><br /><br />Username allready exist. please try another one.";
        else {
            $from = get_option('admin_email');
            $headers = 'From: '.$from . "\r\n";
            $subject = "Registration ok!";
            $msg = "Welcome, you are now registered. Here is your username and password.\Info:\Username: $username\Password: $random_password";
            wp_mail( $email, $subject, $msg, $headers );
            echo "<strong>You are now registered. An e-mail is now sent to you with your username and password..";
        }

        exit();

    } else { ?>

        <form method="post" action="<?php echo site_url('wp-login.php?action=register', 'login_post') ?>" id="registerform" class="col-xs-12" name="registerform">
            <div class="row">
                <div class="col-xs-12 col-md-6">
                    <p>
                        <label for="user_login">Username</label>
                        <input id="user_login" class="input" type="text" size="20" value="" name="user_login">
                    </p>
                    <p>
                        <label for="user_email">Email</label>
                        <input id="user_email" class="input" type="email" size="25" value="" name="user_email">
                    </p>
                    <p>
                        Password <input type="password" name="pass1" size="25" value="">
                        Repeat Password <input type="password" name="pass2" size="25" value="">
                    </p>
                </div>
                <div class="submit">
                    <input id="wp-register" class="button-primary pull-right col-xs-12 col-md-3" type="submit" value="Register" name="wp-submit" tabindex="103">
                    <input type="hidden" value="/login-area/?action=register&success=1" name="redirect_to">
                    <input type="hidden" name="user-cookie" value="1" />
                </div>
            </div>
        </form>

        <script type="text/javascript">                         
        jQuery("#wp-register").click(function() {
            var input_data = jQuery('#registerform').serialize();
            jQuery.ajax({
                type: "POST",
                url:  "<?php echo "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>",
                data: input_data,
                success: function(data){
                    alert('Success');
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(jqXHR.status); // I would like to get what the error is
                }
            });
            return false;
        });
        </script>
<?php }
} else ?>
    Already registered? Login to your account with the form in the sidebar.
<?php } else { ?>
You are already logged in...
<?php } ?>

The PHP seems to work fine as when I console log it I get the right message when there is an error.

How can I show these errors inside the Ajax success or error functions?

The code I'm using always seems to always get to the success function even if there are some errors.

I would like to know what errors there are and print a message with the type of error somewhere on the page and if it's successful I'd like to print a successful message.

2

There are 2 answers

0
Jeff On BEST ANSWER

I managed to find a solution to my problem.

I have used this inside my Ajax function:

success: function(data){
    jQuery(data).find('.message').appendTo('#login-error');
}

And in the php code I have changed for example this:

...    
if(empty($username)) {
    echo "<span style='color:#FF0000'><strong>Error..</strong></span><br /><br />You have to fill in the username.";
    exit();
}
...

to this:

...
if(empty($username)) {
    echo "<span class='message error'>Please enter username.</span>";
    exit();
}
...

I hope this will be helpful to someone.

6
Gary Liu On

success function in AJAX is just the callback function when it get the response of its request.

Your php echos are excellent the responses what AJAX request for. so it also get in success function. So U just can set an array to store a flag of lonin status and the info you want to show like echo josn_encode(['flag'=>true,'info'=>'success']) and in success function just switch the flag and do change the Dom text with the info.