0

I know they are already many questions related to this topic but I was looking for a simple way to make an ajax check for an existing username. So basically I have the HTML form and two functions (in function.php) - one to make the ajax request and the other to make the DB lookup. Note: I'm using WP Multisite.

The HTML Form:

<form method="post" name="register_user">
  <p> 
    <label for="register_name">Name<br> 
    <input type="text" name="register_name" placeholder="Enter your user name"> 
    </label>
  </p>
  <p>
    <label for="register_email">E-Mail<br> 
    <input type="text" name="register_email" placeholder="Enter your E-Mail"> 
    </label>
  </p>
  <p> 
    <label for="register_pass">Password<br> 
    <input type="text" name="register_pass" placeholder="• • • • • • •"> 
    </label>
  <p> 
    <input class="button-large register" type="submit" value="Sign Up">
  </p>

</form>

AJAX call:

function mpl_add_js_login(){
?>

    <script>
    jQuery( document ).ready(function($) {
        $('input[name="register_name"]').change(function (e) {
            var this_field = $(this);
            var user_name = this_field.val();
            $('.uname_status').remove();
            $.ajax({
                url : '<?php echo admin_url( 'admin-ajax.php' ); ?>',
                type: "POST",
                data: {'action': 'check_username', user_name: user_name},
                dataType: "json",
                success: function(response) {
                        this_field.closest('label').append('<div class="uname_status '+ response.text +'">'+response.text+'</div>');
                }
            });
        });
    });



    </script>
<?php
}
add_action('login_footer','mpl_add_js_login');

Username checkup:

function mpl_check_username() {

  $response = array();
    $username = sanitize_text_field($_POST['register_name']);
    if(username_exists($username)){
        $response['status'] = 'unavailable';
    $response['text'] = __('Username unavailable');
    }else{
         $response['status'] = 'available';
     $response['text'] = __('Username available');
    }
    echo json_encode($response);
    die();
}
add_action('wp_ajax_nopriv_check_username', 'mpl_check_username');
add_action('wp_ajax_check_username', 'mpl_check_username');

ERROR: This code always turns to $response['status'] = 'available';even, if you type admin as username. Is there something wrong with the username_exists(); function?

1 Answer 1

0

You're POSTing user_name but in your code you're checking for register_name, you should instead check $_POST['user_name'] instead.

You should also be checking to make sure a value is actually being passed as well, this is how I would do it instead (setting unavailable as default):

function mpl_check_username() {

    $response = array(
        'status' => 'unavailable',
        'text' => __( 'Username unavailable' )
    );

    $username = array_key_exists( 'user_name', $_POST ) ? sanitize_text_field( $_POST['user_name'] ) : false;

    if ( $username && ! username_exists( $username ) ) {
        $response['status'] = 'available';
        $response['text']   = __( 'Username available' );
    }

    echo json_encode( $response );
    die();
}

All the username_exists function does is this code below:

$user = get_user_by( 'login', $username );
if ( $user ) {
    $user_id = $user->ID;
} else {
    $user_id = false;
}

You could also try this in your code to remove the possibility of the username_exists filter being used to return true for some weird reason.

3
  • Oh man thanks! Probably I replaced user_name by register_name because my field has this name, but it doesn't make sense - cause it's the name of the passing parameter. Also is there a way to make the response faster? Or is this limited by my hosting?
    – Game Unity
    Commented Mar 9, 2019 at 20:56
  • You could generate your own cache of all currently used usernames and set that in a javascript variable and then just check that (but that also means all your current usernames would be available in javascript which may not be a good idea). What I would do instead is to add a debounce on the text input, that way you're not querying every single change/press, and say only make the query after 5 second debounce or something
    – sMyles
    Commented Mar 10, 2019 at 19:17
  • Yea fortuitously I did this right away :D So now it's not spamming the howl time Also I made some changes to the JS it's now in a JS file and not inline - also I added a whole checkup system to it.
    – Game Unity
    Commented Mar 10, 2019 at 19:38

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.