Check if username exist with AJAX

I’ve created a custom registration form for a WordPress MultiSite installation. It allows registrations of new blogs and users. I want to check with ajax if a given username is available. This is what I have so far:

add_action( 'wp_footer', 'pb_ajax_add_js' );

function pb_ajax_add_js() {

// add script to the footer
wp_enqueue_script( 'pb_ajax',
    plugin_dir_url( __FILE__ ).'js/script.js',
    array('jquery'), BOJ_ARM_VERSION, true
);

//Get protocol of the current page.
$protocol = isset( $_SERVER["HTTPS"]) ? 'https://' : 'http://';

// Display the admin-ajax.php using the same protocol as the current page.
$params = array(
  'ajaxurl' => admin_url( 'admin-ajax.php', $protocol )
);
wp_localize_script( 'pb_ajax', 'pb_ajax', $params );
}

Server side request handling:

Read More
// Ajax request handling.
add_action('wp_ajax_nopriv_boj_arm_ajax', 'pb_check_username');
add_action('wp_ajax_boj_arm_ajax', 'pb_check_username');

function pb_check_username() {
$username = $_REQUEST['usr'];
echo $username;

die();
}

And jQuery script(note: in this version, validation is after click link)

(function($) {
    $('.check-username').click(function(){
        var link = this;
        $(link).html('sprawdzanie...');
        // href="' . get_permalink() . "#more-{$post->ID}"
        var usr = $("#site-addres-input").attr('value');

        var data = {
            action: 'boj_arm_ajax',
            usr: usr
        };

        $.get(boj_arm.ajaxurl, data, function(data){
            $(link).after(data).remove();
        });
        return false;
    });
})(jQuery);

Script isn’t complete. It Must check if the username exists, and return true or false. Can You help me Please?

Related posts

Leave a Reply

2 comments

  1. The problem is with your jQuery selector:

    var usr = $("#site-addres-input").attr('value');
    

    Will get the default value of the input element. Typically this will be blank, because you’re not setting it ahead of time. You need to use:

    var usr = $("#site-addres-input").val();
    

    I’m also noticing that you’re using #site-addres-input, but “address” has two s at the end. Not sure if this is also causing you a problem or not …

  2. You can use this function: username_exists to check if the user exists.
    Like this:

    add_action('wp_ajax_nopriv_boj_arm_ajax', 'pb_check_username');
    add_action('wp_ajax_boj_arm_ajax', 'pb_check_username');
    
    function pb_check_username() {
        $username = $_REQUEST['usr'];
        if(username_exists($username))
            echo 1;
        else
            echo 0;
        die();
    }
    

    Please read the codex for the correct usage of this function as you’ll need to include a file.