I realize that there’s already a lot of tutorials like this out there, but I recently needed to show a friend how to do a unique username check for a registration form via AJAX, so figured I’d share the results as it’s easier than you might think.

First off, the html. I was incorporating this into an existing site, so I just put together some quick html for testing with a username field. Note the included jQuery and script file.

<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>
			title
		</title>
		<script type="text/javascript" src="jquery-1.4.4.min.js" charset="utf-8"></script>
		<script type="text/javascript" src="ajax.js" charset="utf-8"></script>
	</head>
	<body>
		<input type="text" id="username" value="" />
	</body>
</html>

Pretty straightforward. Other than the script includes, the only relevant thing here is the input field with id=”username”.

The only part I dislike about AJAX development is that you pretty much have to build your JS and your PHP in tandem, and that means mentally switching language contexts on-the-fly. Not a huge deal, but it would be great if I was using something like node.js so that I could just focus on a single language. Rather than showing you the code then explaining it line-by-line, I’ve decided to use verbose inline comments. This way if you decide to just copy/paste, at least you’ll have an explanation of what’s going on when you look at it later.

We’ll start with ajax.js

/*
noConflict() required as the existing site uses another library that includes $()
*/
$j = jQuery.noConflict();

/*
Standard jQuery (document).ready()
Begins processing the enclosed function once the DOM is loaded
*/
$j(document).ready(function() {
	/*
	Makes an AJAX call to check the given username against existing names in the DB
	*/
	function checkUser(username) {
		/*
		This is where the magic happens. jQuery .get() function is very straightforward.
		The first parameter I used is the php file that will doing the actual SQL query.
		I pass it username as a parameter in the query string.
		The second parameter is the callback function that will be executed when the
		PHP function has finished executing. This function's argument - data - will
		contain the data that is echoed from the PHP function.'
		*/
		$j.get(
			'checkuser.php?username=' + username,
			function(data) {
				/*
				The data is passed from the PHP file as a JSON-encoded string,
				so we parse the data and are left with a standard JS object
				*/
				data = JSON.parse(data);
				alert('Username ' + data['username'] + ' is ' + data['available']);
			}
		);
	}
	
	/*
	Here we bind the blur event of the #username field to a simple function which retrieves
	its value and passes it to the checkUser() function above
	*/
	$j('#username').bind('blur', function() {
		var username = $j(this).val();
		checkUser(username);
	});
});

Next we have checkuser.php, our PHP file that will actually check the DB for the username and return an object to our JS callback function indicating whether or not the name is available.

<?php
function check_username( $username ) {
	/*
	Create a new object and add username to its username property
	*/
	$data = new stdClass();
	$data->username = $username;
	/*
	SQL query. This assumes you've already set up a connection somewhere.
	Note that $username is being escaped. This is to prevent SQL injection attacks.
	Also you'll likely need to change your field and table names to match your own
	environment.
	*/
	$sql = "SELECT username FROM tablename WHERE username='" . mysql_real_escape_string( $username ) . "'";
	/*
	In this case, mysql_query returns an array of records or false if an error occurs or no records exist.
	Additional error handling should be built in to account for connection problems.
	*/
	$ret = mysql_query( $sql );
	/*
	Explicitly check for false as a return value
	*/
	if ( $ret === false ) {
		/*
		If false (i.e. no rows were returned with the queried username),
		that name is available
		*/
		$data->available = 'available';
	}
	else {
		/*
		Username is already taken
		*/
		$data->available = 'not available';
	}
	/*
	JSON encode the data and echo it back to the JS callback function
	*/
	echo json_encode( $data );
}

/*
Checks for username as part of the query string, and if it exists passes it
to the check_username() function
*/
if ( $_GET['username'] ) {
	check_username( $_GET['username'] );
}
?>

And that’s it. You now have an AJAX-ified username checker. Obviously this can be extended to all kinds of different uses / scenarios, which I’ll leave up to your imagination.

If you have any issues, feel free to ask me in the comments.