1

Update 2.1:

Okay, after messing around with this some more I remembered that I hadn't included the JS file which was causing the white screen, OOPS! ;)

Now the form does not submit the data nor send the email ... also the error handling is still not working.


I have a registration form that runs on the wp_create_user function so that I can limit who registers to my site! I'm now trying to AJAXify it for error handling and a "smoother" and more relaxed user experience.

After taking @Andrew Bartel's advice I buckled down and applied myself to "at least try" to move in the right direction.

So here's my updated issue: for some reason, unknown to me, my page still wants to refresh when the form is submitted .. but when it does it doesn't refresh to the "same page" instead the whole screen goes white with no errors or anything. I'm completely lost!

Here are the files/code that I'm working with...

The registration form (custom-uploader.php):

<h1 class="register-header">Register a new user</h1>

<a class="logout" href="<?php echo wp_logout_url( get_permalink() ); ?>">Logout</a>

<div id="form-messages"></div>

<form id="register-form" method="post" action="<?php echo plugins_url( 'register.php', dirname( __FILE__ )); ?>">
    <!-- Username -->
    <p>
        <input type="text" name="user_name" id="user_name" class="input" placeholder="unique username" required>
    </p>

    <!-- Email to send p/w to -->
    <p>
        <input type="email" name="user_email" id="user_email" class="input" placeholder="email address" required>
    </p>

    <!-- Hidden Nonce "input" -->
    <?php wp_nonce_field( 'nonceification', 'register_nonce' ); ?>

    <p class="small-text">You will receive an email with a generated password<br />(which you can change in your "user settings")</p>
    <button type="submit" id="wp-submit" class="btn">Register new user</button>
</form>

Attempted AJAX file (register.js)

jQuery.noConflict();

jQuery(function() {

    // Get the form.
    var form = jQuery('#register-form');

    // Get the messages div
    var formMessages = jQuery('#form-messages');

    // Set up an event listener for the contact form
    jQuery(form).submit(function(event) {

            // Stop the browser from submitting the form
            event.preventDefault();

            // Serialize the form data
            var formData = jQuery(form).serialize();

            jQuery.ajax({
                    type: 'POST',
                    url: jQuery(form).attr('action'),
                    data: formData 
            }).done(function(response) {

                    // Make sure that the form Messages div has the 'success' class
                    jQuery(formMessages).removeClass('register-error');
                    jQuery(formMessages).addClass('register-success');

                    // Set the message text
                    jQuery(formMessages).text(response);

                    // Clear form
                    jQuery('#user_name').val('');
                    jQuery('#user_email').val('');
            }).fail(function(data) {

                    // Make sure that the formMessages div has the 'error' class
                    jQuery(formMessages).removeClass('register-success');
                    jQuery(formMessages).addClass('register-error');

                    // Set the message text
                    if(data.responseText !== '') {

                            jQuery(formMessages).text(data.responseText);
                    }else{
                            jQuery(formMessages).text('Oops! An error occurred and your request was not sent.');
                    }
            });
    });
});

The actual registration process (register.php)

<?php

require_once( '/home5/desigoe6/public_html/demo/dominion-skills/wp-load.php' );

$username = $_POST['user_name'];
$email = $_POST['user_email'];

// Verify nonce field
$nonce = $_POST['register_nonce'];
if ( !wp_verify_nonce( $nonce, 'register_nonce' )) {

    die();
}

// Sanitize user input data
$username = sanitize_user( $username, $strict = true );
$email = santize_email( $email );

// Validate email format
$email_val = filter_var( $email, FILTER_VALIDATE_EMAIL );

// Check if user's chosen name/email already exists
$user_id = username_exists( $username );
$user_email = email_exists( $email );

// Parse data, if 'good' execute
if ( $user_id && $user_email ) {

    http_response_code(400);
    echo "Oops! There appears to be an account already with that name and/or email.";
    exit;

} elseif ( !$email_val ) {

    http_response_code(400);
    echo "Please enter a valid email and retry!";
    exit;

} else {

    // Generate the password and create the user
    $password = wp_generate_password( 12, false );
    $user_id = wp_create_user( $username, $password, $email );

    // Update user
    wp_update_user( array( 'ID' => $user_id ));

    // Set user role
    $user = new WP_User( $user_id );
    $user->set_role( 'subscriber' );

    // Email user their password
    $mail = wp_mail( $email, 'Your new password!', 'Here\'s your new password: ' . $password );

    if ( $mail ) {

        http_response_code(200);
        echo "Success! Check your email for your password! Logout and use your new username & password.";
    } else {

        http_response_code(500);
        echo "Um, it looks like there was any error and we failed to receive your request ... if this problem persists please let us know!";
    }
}?>

Also, if you see any other flaws or "bad practices" being put to use in this, please, let me know ... I'm still trying to wrap my head around how this stuff works.

Thanks!

4
  • 1
    Have you tried ajaxifying it at all yet? Where are you stuck? Commented May 15, 2014 at 1:09
  • @AndrewBartel: I'm not sure where to start! I'm still a bit unfamiliar with AJAX. Commented May 15, 2014 at 1:58
  • So, the question is borderline over-broad because there's several different questions being asked. Like, how do I do javascript validation on my form, passing that, how do I make an ajax request in WordPress, and how do I parse that response to display either an error or success message? And that's leaving out things like a nonce check or sanitization on the submitted data. What you're asking seems like a complete copy/paste solution rather than help with a specific problem you encountered during development. If you give it a shot, I'm sure people will be happy to help. Commented May 15, 2014 at 4:20
  • @AndrewBartel: Thank you for your encouragement to at least try ... I realize I was being a bit lazy when I first asked! I have taken your advice and after much research have been able to "try"; however I'm now at a loss as to why it's not working. Could you check out my updated question and see if you can tell what might be going on? Commented May 16, 2014 at 15:17

1 Answer 1

1

I think that main problem here is that you try to use "fail" to indicate the state where form has errors. This is wrong, because ajax call will "success" even when form will have errors, because from jquery point of view - it made a ajax call and got response.

Fail will be called only on 404 errors etc.

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.