Check Username Availability Using PHP And Jquery

In a registration form there is a need to check the available user name. Using ajax request to check available username is a good idea. It is required and reduce users’ effort while registering for a new account. You have seen this kind of arrangement in Gmail sign up form for validation of available email address.

For this, you need to check whether the username exists or not dynamically. You can do it with the help of jQuery and PHP. First of all create an HTML form. Then use jQuery to call a PHP file. This Php file will check the available usernames in database.

See the code of all files below.

JQuery Code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function checkUserName(usercheck)
{
$('#usercheck').html('<img src="images/ajax-loader.gif" />');
$.post("checkuser.php", {user_name: usercheck} , function(data)
{
  if (data != '' || data != undefined || data != null)
  {
 $('#usercheck').html(data);
  }
          });
}
</script>

CSS code

body{
padding:0;
margin:0;
font-family:"Trebuchet Ms";
color:#2a2a2a;
font-size:14px;
line-height:18px;
}

.error{
color: #FF0000;
font-size:11px;
}

.success{
color: #33CC00;
font-size:11px;
}

Php code:

<?php

$arr_user=array("username1", "username2");
$username=$_POST['user_name'];

if(in_array($username,$arr_user))
{echo '<span class="error">Username already exists.</span>';exit;}
else if(strlen($username) < 6 || strlen($username) > 15){echo '<span class="error">Username must be 6 to 15 characters</span>';}
else if (preg_match("/^[a-zA-Z1-9]+$/", $username))
{
       echo '<span class="success">Username is available.</span>';
}
else
{
      echo '<span class="error">Use alphanumeric characters only.</span>';
}
?>

HTML code:

<div style="padding:100px 0px  50px 10px;">
Username : <input type="text" name="username" id="username" onblur="checkUserName(this.value)" />
<span id="usercheck" style="padding-left:10px; ; vertical-align: middle;"></span>
</div>

Integrate these codes.

In php code, I have used array for used username. for a real time application you will have to fetch used username from database. If you have any kind of problem in implementing that, you can ask via comments.

Advertisement


Deepanker Verma is the founder of Techlomedia. He is a tech blogger, developer and gadget freak.


Similar Articles

0 Comments

Leave a comment

Comment policy: We love comments and appreciate the time that readers spend to share ideas and give feedback. However, all comments are manually moderated and those deemed to be spam or solely promotional will be deleted.

2020 UseThisTip | Part of Techlomedia Internet Pvt Ltd Developed By Deepanker