Did you notice how many sites have a verification tool for the ‘username’ field when you try to register? Many use the power of AJAX to check if the nickname has already been assigned to an existing member. This short tutorial gives you an idea of how you can make such a feature in the pages of your website. We’ll use JavaScript (JQuery) and PHP.

Let’s start creating the page where the visitor will type the “username”:

index.php

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE>An AJAX Username Verification Tool</TITLE>
  <META NAME="Keywords" CONTENT="form, username, checker">

  <META NAME="Description" CONTENT="An AJAX Username Verification Script">

<script type="text/javascript" src="jquery-1.2.6.min.js"></script>

<link rel="stylesheet" type="text/css" href="style.css" />

As you can see the JQuery library and the CSS file (will reveal its contents later) are included. Now let’s continue creating the script that takes the input value and sends it to check.php in order to determine if the username is already in use or not. I will explain you the code in detail below.

<SCRIPT type="text/javascript">
<!--
/*
Credits: Bit Repository
Source: http://www.bitrepository.com/web-programming/ajax/username-checker.html
*/

pic1 = new Image(16, 16);
pic1.src="loader.gif";

$(document).ready(function(){

$("#username").change(function() { 

var usr = $("#username").val();

if(usr.length >= 4)
{
$("#status").html('<img src="loader.gif" align="absmiddle">&nbsp;Checking availability...');

    $.ajax({
    type: "POST",
    url: "check.php",
    data: "username="+ usr,
    success: function(msg){  

   $("#status").ajaxComplete(function(event, request, settings){ 

	if(msg == 'OK')
	{
        $("#username").removeClass('object_error'); // if necessary
		$("#username").addClass("object_ok");
		$(this).html('&nbsp;<img src="tick.gif" align="absmiddle">');
	}
	else
	{
		$("#username").removeClass('object_ok'); // if necessary
		$("#username").addClass("object_error");
		$(this).html(msg);
	}  

   });

 } 

  }); 

}
else
	{
	$("#status").html('<font color="red">' +
'The username should have at least <strong>4</strong> characters.</font>');
	$("#username").removeClass('object_ok'); // if necessary
	$("#username").addClass("object_error");
	}

});

});

//-->

</SCRIPT>

Read more from this entry…