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?