1

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.

3 Answers 3

0

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

The jQuery error is triggered, when the request itself fails, for example timeout and others. See the jQuery documentation.

The error messages, which are produced by PHP appear only on request success.

To display these, you could do for example:

            success: function(data){
                jQuery( data ).appendTo( 'body' );
            }

It will need some styling though :)

EDIT: Since in your script it is possible, the whole form-element will be outputted, you can prevent this by using regular expressions in the success-callback:

        success: function(data){
            if( ! data.match( /<form/ ) )
                jQuery( data ).appendTo( 'body' );
        }

So you can use regular expressions to prevent appending output, you might not want to output.

3
  • Thank you for this. I have tried that but it appends the entire page. Is it possible to only append the error or success messages?
    – Jeff
    Commented Jun 9, 2015 at 10:26
  • updated my answer Commented Jun 9, 2015 at 10:32
  • Thanks for your help but when I add that nothing happens. The post request works but nothing shows on the page. It feels like I'm almost there..! So frustrating
    – Jeff
    Commented Jun 9, 2015 at 10:54
0

Thanks to @websupporter 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 done this:

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

I hope this will be helpful to someone.

1
  • you should mark your question as answered :) Commented Jun 10, 2015 at 6:47
0

I ran into same problem. Any of above didn't work for me. Please make sure you set the dataType of your ajax call to 'html' not 'json'

Sample code:

$.ajax({
    url: ajaxurl,
    type: 'POST',
    dataType: 'html',
    cache: false,
    data: { data: data, action: 'jseditajax' }
})
.done(function(response) {
    response = response.slice(0, - 1); // removing 0 at last string position
    response = JSON.parse(response); // string to JSON

    console.log(response);
});

And in your PHP file you can simply -

echo json_encode($your_array);

I hope this helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.