I thought I would help out people who want to use jQuery, Ajax and php to check to see if a username isn’t already in the database table. Here we go:
First you have something like this in your HTML form:
<input type="text" id="regName" name="username" placeholder="Enter Username" tabindex="4" required>
Second, you would do something like this in your jQuery script (or something close to it):
[php]$(’#regName’).on(‘focusout’, function(event) {
var username = $(this).val();
var params = { action: ‘checkName’, username: username }; // Set parameters
var myData = jQuery.param( params ); // Set parameters to corret AJAX format
$.ajax({
type:"post",
url:"checkuser.php",
data: myData,
success:function(info){
if (info) {
$registerLegend.text('Username is already taken, Please Re-Enter');
$registerLegend.css('color', 'red');
$('#regName').val(' ');
} else {
$registerLegend.text('Register');
$registerLegend.css('color', '#000');
}
}
}); // End of Ajsx Function
}); // End of Username Check for Duplicates[/php]
and lastly the php script would look something like:
[php]<?php
include ‘lib/includes/utilities.inc.php’;
if ( isset($_POST[‘action’]) && $_POST[‘action’] == ‘checkName’) {
$username = $_POST['username'];
$query = 'SELECT 1 FROM users WHERE username=:username';
$query_params = array( ':username' => $username);
$stmt = $pdo->prepare($query);
$result = $stmt->execute($query_params);
$row = $stmt->fetch();
if ($row) {
echo true;
} else {
echo false;
}
}[/php]
Keep in mind that I’m assuming you know how to make a database connection and that the PDO error handling isn’t robust in the example script (Well there isn’t any ;D). Hopefully, someone might find this useful.