Checking to see if username isn't already being used?

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.

What are the pro’s and cons for those who may not know? I.e. why use Ajax, JQuery, PHP & HTML to do a job that PHP/HTML will do?

Also, what about a fall back if Javascript is disabled? I know it’s rare, but there are still some old school people who would have JS disabled, or if you were accessing a webpage on a server for example (not that you would as you’d disable the browser completely).

Are there any speed/space/bandwidth benefits, or is it just to make it look and act pretty?

As a programmer, which way would you recommend, using the flashy stuff or bog-standard PHP/HTML?

Sponsor our Newsletter | Privacy Policy | Terms of Service