How to Check Username Availability using jQuery + PHP

November 3rd, 2009 by dr.emi

Hi! dude! how are you today ? I hope all of you will fine :)

Today is our nice day, it’s time to party. Let’s learn again about jQuery and PHP. How to create safety validation of username checker for your member register using jQuery and PHP ? Check it now!

However we still need :

Member register form, just a simple HTML code

jQuery library, the Ajax Masterpiece

PHP Script, basic validation script

Little bit of member sql table, we will create it using PHPMyAdmin

Now, open your Dreamweaver, or any Code Editor, Notepad++ are welcome!

First, we will create HTML code for member register form. Remember, this form is just for illustrate the real form.

<form id="form1" name="form1" method="post" action="">
<fieldset>
	<legend>Check Username Availability</legend>
	<label>Username <span class="require">(* requiered: alphanumeric, without white space, and minimum 4 char</span></label>
    <input type="text" name="username" id="username" size="15" maxlength="15" onchange="loadContentResult(this.value)" />
	<div id="spinner"></div>
    <div id="actionresult"></div>
	<div class="clear"></div>
	<label>Email:</label>
	<input type="text" name="email" id="email" size="30" maxlength="255" />
	<div class="clear"></div>
	<input type="submit" name="submit" id="submit" value="Register" />
</fieldset>
</form>

On my input code, I use onchange=”loadContentResult(this.value)” to handle username field value while onChange event. So, where is come from the loadContentResult() ?

Here are the Javascript code, include for jQuery preloader.

<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
// Count the number of times a substring is in a string.
String.prototype.substrCount =
  function(s) {
    return this.length && s ? (this.split(s)).length - 1 : 0;
  };

// Return a new string without leading and trailing whitespace
// Double spaces whithin the string are removed as well
String.prototype.trimAll =
  function() {
    return this.replace(/^\s+|(\s+(?!\S))/mg,"");
  };

//event handler
function loadContentResult(username) {
	if(username.substrCount(' ') > 0)
	{
		$("#actionresult").hide();
		$("#actionresult").load("user.php?msg=whitespace", '', callbackResult);
	}
	else
	{
		$("#actionresult").hide();
		$("#actionresult").load("user.php?username="+username.trimAll()+"", '', callbackResult);
	}
}

//callback
function callbackResult() {
	$("#actionresult").show();
}

//ajax spinner
$(function(){
	$("#spinner").ajaxStart(function(){
		$(this).html('<img src="image/wait.gif" />');
	});
	$("#spinner").ajaxSuccess(function(){
		$(this).html('');
 	});
	$("#spinner").ajaxError(function(url){
		alert('Error: server was not respond, communication interrupt. Please try again in a few moment.');
 	});
});
</script>

To call jQuery library, use

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

You must carefull to validate string from username field before send it into PHP script. The problem is if you enter white space string from username field then send it into PHP script without validate it before, you will trouble while accessing user.php as PHP Script. So I need to add this javascript before validated by PHP script.

// Count the number of times a substring is in a string.
String.prototype.substrCount =
  function(s) {
    return this.length && s ? (this.split(s)).length - 1 : 0;
  };

// Return a new string without leading and trailing whitespace
// Double spaces whithin the string are removed as well
String.prototype.trimAll =
  function() {
    return this.replace(/^\s+|(\s+(?!\S))/mg,"");
  };

How about jquery as script loader? To load user.php and attempt it into DIV ID for #actionresult, we can use this script:

//event handler
function loadContentResult(username) {
	if(username.substrCount(' ') > 0)
	{
		$("#actionresult").hide();
		$("#actionresult").load("user.php?msg=whitespace", '', callbackResult);
	}
	else
	{
		$("#actionresult").hide();
		$("#actionresult").load("user.php?username="+username.trimAll()+"", '', callbackResult);
	}
}

//callback
function callbackResult() {
	$("#actionresult").show();
}

Don’t worry about ajax loading animation, I use simple GIF animation as spinner:

//ajax spinner
$(function(){
	$("#spinner").ajaxStart(function(){
		$(this).html('<img src="image/wait.gif" />');
	});
	$("#spinner").ajaxSuccess(function(){
		$(this).html('');
 	});
	$("#spinner").ajaxError(function(url){
		alert('Error: server was not respond, communication interrupt. Please try again in a few moment.');
 	});
});

So, what netxt!? It’s time to make cool PHP Script to validate our username string (in this case, I just use username field as POST variable. But before it, let’s create our mysql table:

CREATE TABLE `member2` (
`member_id` int( 11 ) NOT NULL AUTO_INCREMENT ,
`username` varchar( 15 ) NOT NULL ,
`email` varchar( 255 ) NOT NULL ,
PRIMARY KEY ( `member_id` )
);
INSERT INTO `member` VALUES (1, 'dremi', 'webmaster@dremi.info');

This script for user.php file as response validator. Remember this is main function only, you may add some connection script.

function clearString($value)
{
	if (get_magic_quotes_gpc())
	{
		$value = stripslashes($value);
	}
	if (!is_numeric($value))
	{
		$value = mysql_real_escape_string($value);
	}
	$value = trim(strip_tags($value));
	return $value;
}

function validStr($str, $num_chars, $behave) //alpha numeric only for entire of string width
{
	if($behave=="min")
	{
		$pattern="^[0-9a-zA-Z]{".$num_chars.",}$";
	}
	elseif($behave=="max")
	{
		$pattern="^[0-9a-zA-Z]{0,".$num_chars."}$";
	}
	elseif($behave=="exactly")
	{
		$pattern="^[0-9a-zA-Z]{".$num_chars.",".$num_chars."}$";
	}

	if(ereg($pattern,$str))
	{
		return true;
	}
	else
	{
		return false;
	}
}

And this is for validate condition.

$username	= $_REQUEST['username'];
$msg		= $_REQUEST['msg'];

if(isset($username) && $username != '')
{
	if(validStr($username, 4, 'min') == false)
	{
		?>
		<span style="color:red">You enter invalid username</span>
		<?php
	}
	else
	{
		connect(_HOST, _USER, _PASS, _DB);
		$jCekMember = numrows(query("SELECT * FROM member WHERE username = '".clearString($username)."'"));
		if($jCekMember != 0)
		{
			?>
			<span style="color:blue">Username <?php echo $username; ?> was unavailable, another people has taken.</span>
			<?php
		}
		else
		{
			?>
			<span style="color:green">Username <?php echo $username; ?> available.</span>
			<?php
		}
		close();
	}
}
elseif($msg == 'whitespace')
{
	?>
	<span style="color:red">Username cannot contain of white space</span>
    <?php
}
else
{
	?>
	<span style="color:red">Insert username</span>
    <?php
}

While username is valid string, PHP script will check availablility on member table using this code:

$jCekMember = numrows(query("SELECT * FROM member WHERE username = '".clearString($username)."'"));

So, as showed on next line, if username is not available to register in member table, it’s mean the username has taken by another people, and message will say :

Username <?php echo $username; ?> was unavailable, another people has taken.

Well, everything is gonna be Allright :)
Now let’s see the result by click on Demo Button or you can Download full code to learn.

Popularity: 27% [?]

Download Demo
Bookmark Subscribe
Hello my fox! Glad to see you today!

If you love my tutorial, please chose any action from the left button.

4 Comments

sahrui Said:  

nice tutorial….thx bro !

zoel Said:  

Trima Kasih buat tutorialnya, sangat bermanfaat.

DONNY SANJAYA Said:  

tutorial yang mantap bro…
ijin dowload..

dr.emi Said:  

@DONNY
ok bero…..

Hi.. ! Wanna say anything about my tutorial ?
Just say it with fill the comment form.
Comment Form
 

 
 
 
 
 
Category
stack

Switch to our mobile site