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)

  -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)





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: