So you are creating a signup form and you want to create a fancy looking username validation Ajax script. I know that looks fancy when you signup for Gmail or Yahoo mailbox, instead these kind of validation are now on every signup form.

We are going to create this simple script using Javascript, Ajax, and of course PHP for the server interaction. In this PHP script I have not shown how you can validate it using mysql, since that is not the motive of this article. So all you have to do is implement the MYSQL logic so that it returns you proper result of the username availability. I am using a boolean variable called $available in PHP script. You can turn it ON & OFF (using true and false) to test the working of complete script. Demo of this script can be checked on this Demo Page.

The server side logic for the username availability (validate.php)

<?php
 
$user = strip_tags(trim($_REQUEST['username']));
 
if(strlen($user) <= 0)
{
  echo json_encode(array('code'  =>  -1,
  'result'  =>  'Invalid username, please try again.'
  ));
  die;
}
 
// Query database to check if the username is available
$query = "Select * from USERS where username = '$user' ";
// Execute the above query using your own script and if it return you the
// result (row) we should return negative, else a success message.
 
$available = true;
 
if($available)
{
  echo json_encode(array('code'  =>  1,
  'result'  =>  "Success,username $user is still available"
  ));
  die;
}
else
{
  echo  json_encode(array('code'  =>  0,
  'result'  =>  "Sorry but username $user is already taken."
  ));
  die;
}
die;
?>

The HTML and ajax code.(validate.html)

<script type="text/javascript">
  //function to create ajax object
  function pullAjax(){
    var a;
    try{
      a=new XMLHttpRequest()
    }
    catch(b)
    {
      try
      {
        a=new ActiveXObject("Msxml2.XMLHTTP")
      }catch(b)
      {
        try
        {
          a=new ActiveXObject("Microsoft.XMLHTTP")
        }
        catch(b)
        {
          alert("Your browser broke!");return false
        }
      }
    }
    return a;
  }
 
  function validate()
  {
    site_root = '';
    var x = document.getElementById('uname');
    var msg = document.getElementById('msg');
    user = x.value;
 
    code = '';
    message = '';
    obj=pullAjax();
    obj.onreadystatechange=function()
    {
      if(obj.readyState==4)
      {
        eval("result = "+obj.responseText);
        code = result['code'];
        message = result['result'];
 
        if(code <=0)
        {
          x.style.border = "1px solid red";
          msg.style.color = "red";
        }
        else
        {
          x.style.border = "1px solid #000";
          msg.style.color = "green";
        }
        msg.innerHTML = message;
      }
    }
    obj.open("GET",site_root+"validate.php?username="+user,true);
    obj.send(null);
  }
</script>
<style>
#uname{border: 1px solid #000;}
</style>
<input type="text" id="uname" name="uname" value="" />
<input type="button" onclick="validate();" value="Check Availability" />
<div id="msg"></div>

How to make it work
It is very simple to make this script work. You need two files, a HTML file (say, validate.html) and a PHP file (say, validate.php) to interact with the database and check for the availability of the required username. Keep both files in same folder for making it to work correctly, otherwise if you want to keep the PHP file somewhere else, then you can specify the absolute path using the “site_root” variable defined in Javascript. You can also keep the Javascript code in separate JS file to keep the code clean. The most important thing is to keep the id names of the HTML elements same as the ones you are going to use in the JS code.

So now you have your own Signup form with bells & whistles. Hope this code helps you. Some may not be comfortable in using eval in the Javascript code, you can deal with JSON the way you like to.

 

Stay Digified !!
Sachin Khosla

Share this post: