I currently have a working registration form I created on my page. It's an HTML form and I coded PHP to have it create the user in our WP_user table and email us with info from the form. The PHP is in the functions.php file, and there are no issues with it working but it currently has to be submitted and if the created username already exists, it will show error message on blank index page and then redirect back to the form. WE would like it to validate and show if the username is available or not while on the form. I think this has to be done with AJAX but I'm not sure. Here is the PHP code from functions.php:
if (username_exists($user)){
echo 'Username already exists. Please wait while we redirect you back to the form';
die("<meta http-equiv=\"refresh\" content=\"5;url=".$_SERVER['HTTP_REFERER']."\"/>");
}
if ( !username_exists( $user ) && !email_exists( $email ) ) {
$user_id = wp_create_user( $user, $pass, $email );
if( !is_wp_error($user_id) ) {
//user has been created
$user = new WP_User( $user_id );
$user->set_role( 'subscriber' );
wp_mail( $to, $email_subject, $message, $headers);
//Redirect
wp_redirect( 'http://www.dev.smithhonig.com/thank-you' );
exit;
} else {
//$user_id is a WP_Error object. Manage the error
}
}
Again, this works perfectly but we want to try an option to validate while on the form when the username field is clicked out of. I'm not familiar with AJAX too much or where to implement it for WP so I want to use the best practices here. Thank you
UPDATE:
Here is some code for the AJAX call I'm using.
jQuery(document).ready(function(){
jQuery('#username').on('change', function(){
let user = jQuery(this).val();
jQuery.ajax({
type: 'POST',
url: '<WP_AJAX_URL_HERE>',
data: {action: 'verify_username', username: user},
success: function(data){
console.log(data);
// Write code to show the message to user here
},
error: function(err){
console.log(err);
}
});
});
});
As well as additional PHP in the functions file:
add_action( 'wp_ajax_verify_username', 'check_username' );
add_action( 'wp_ajax_nopriv_verify_username', 'check_username' );
function check_username(){
$username = $_POST['username'];
if( username_exists( $username ) ) {
echo $username . ' already taken.';
}else {
echo 'Hurray ' . $username . ' is available.';
}
exit;
}
let
itself looks fine - hard to say what might cause the error without seeing the message. The JavaScript should be fine whether in an external script or a script block somewhere in the document, so long as the jQuery lib itself is referenced first. In general, it looks like it should work, to me - so long as<WP_AJAX_URL_HERE>
contains the correct URL (you can usewp_localize_script()
to pass this URL to your JavaScript).