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: 60% [?]
Hello my fox! Glad to see you today!If you love my tutorial, please chose any action from the left button.
2 Comments
Just say it with fill the comment form.
My Friends Link
10001 Inspirasi 4w1n.Blogspot.Com Afial blog Afotsum.CO.NR Alfikry Blogspot Ancaran.Com Andrian.Blogdrive.Com AngsaRea AraZidsi Arteknindo.Com ArtheZoo.TK Articlecillin Belajar Gratis Blog Si Bochan BloGila_U2.Blogdrive.Com BOGIRO Book and Movie Review Can_Dra Blog Catalog-Tutorial CatatanLou.110mb.Com Coin-Kevin DataBagus.Com Dede Permana, S. Kom (PT. BITA Bandung) Deniall.Com Desire 8 Distro & Clothing Diplomski.Com Ensept.Com Esato.Com Faris Wijaya FarisW.Com Blog Fendix Wordpress Foxxed-ART Gadget and Tech Gedex.Web.ID GejalaGila.Com GraphicVN HendiHen.Com Henny Indrianty Hmzaky-dot.Blogspot.Com I D I K IDWebHost.BIZ IDWebHost.Com Ilivetodesign.Com Ilmu Grafis Inez Nugroho Irenk Design IT Club Lombok Jafair.Multiply.Com Jaloe Blog Spot Jenggot Community JiranKubur Jurnal Jaloee K B M S Blog Klik-Kanan.Com LearnSimply LensaDarbi MadeInAra – Graphic Design Mark Xaviar Mifka.Multiply.Com More Tech Tips! Ngetixide.Wordpress.Com Nursingmedia.Blogspot.Com OneMoment.CO.NR PC MILD Percikan Iman Bandung Profit Trading Forex Pulsa Center PuwaSila Denpasar Rumah Sakit Herbal SEO Articles and Newsletters Seputar Info Wanita {Niella Anwar} SMKN 3 Batu Supermodel and Celebrity Tedy Blog TeguhNET Articles The-Sulton.Com TopBlogArea.Com Tutorial Flash – Blog Apri Tutorial Website Ubaid UdaraMaya.Com WebDesigner.Web.ID Yudha Yudhanto, S. KomAdvertise
Sponsors
Most Popular Posts
- Membuat Manajemen Hak Akses User dengan Codeigniter
- Interactive Ajax Data Management with Codeigniter
- Web Design Layout Plus Implementasi jQuery Tab Content
- Simple Swing Login Form And getText()
- Web Base Controller System with NirCMD
- Create a simple application to open an EXE file on the window with JAVA
- How to Check Username Availability using jQuery + PHP
- dreLogin v.2.0 Has Release
- The Chain Tutorial from FuelYourCreativity
- Email untuk Pak ESBEYE di HUT RI ke 65
Category
Subcribe RSS Feed
Translate
Flick Group dr.emi
dr.emi creative design
SEO Articles & Newsletters
Forum dremi.info
Free Download
Recent Comments
- dr.emi: @ade itu make toggle nya jQuery: http://api.jquery.com/slid...
- dr.emi: ma sama..... mas berok...
- dr.emi: ada mas berok: http://www.dremi.info/tutorials/jquery/drelo...
- datih: apakah ada syntak Log-in php ???...
- Armin: ngakalin rounded corner biar compatible di semua browser kek...
- Armin: edan ini, tutorialnya langsung sehalaman...gkgkk.. sukses b...
- erny: kereeennn... makasiihhh... kapan2 balik lg! hehehe. :D...
Recent Posts
- MARJINAL DI TVONE "RADIO SHOW"
- Mail Yahoo make me frustrating
- Sharing Pengalaman menggunakan CI dan CakePHP
- Lowongan Kerja dr.emi creative design - Oktober 2011
- Happy Eid Mubarak - May God Bless You!
- Lowongan untuk PHP Programmer (PT Xsis Mitra Utama)
- Fenomena ustad/ustazah jadi2an di tipi sedang marak
- Sayang sekali tak dapat nonton Marky Ramones
- [FIX] Installing Ruby on Rails 3, MySQL and SOLVE few problem on UBUNTU 10.10 (Maverick)
- Small Tip, big solution in SVN Problem
Archives
Popular Tags
3D illustration abstract design adsense aero button animation banner clean navigation codeigniter colouring layer CSS tutorials effect form interface glassy effect google gradient style GUI photoshop design hacker handcoded HTML indonesian culture IT job jQuery layer mask logo lowongan kerja merancang web pen tool photo retouch photoshop design PHP PHP Advance PHP login php programmer product demo relationship search engine shapping spirit text effect transparent gradient web articles web design web development web header web layout web tips





















PSD Files
PHP Source Code






