Jesin's Blog

Welcome to the Portal of Technology

  • Facebook
  • GitHub
  • RSS
  • Twitter
  • Home
  • Categories
    • Domains
    • Linux
    • Networking
    • PHP
    • Virtualization
    • Web Design
    • Web Servers
    • Windows
  • WordPress Plugins
    • Custom Error Pages
    • HTTP Digest Authentication
    • Mailgun Email Validator
  • Toolbox
    • DNS Lookup Tool
    • htdigest Generator Tool Online
    • htpasswd Generator Tool Online
    • HTTP Headers Lookup Tool
    • MD5 Encryption Tool
    • Open Port Check Tool
    • SHA-1 Encryption Tool
    • URL Encoding/Decoding Tool
  • About Me
  • Contact Me
  • Sitemap
Home ›
Web Design ›
Username availability check with AJAX and PHP

Username availability check with AJAX and PHP

March 13, 2013 Web Design Jesin A 6 Comments

web design category thumbnail

Recently the AJAX bug bit me and I started rewriting the code of htdigest generator, htpasswd generator and URL encoder/decoder after learning some basics from w3schools.com. I tried creating a username availability validator using AJAX and it worked well so I am here writing this article on how to do this. I will be concentrating more on the AJAX part and less on PHP because I have already written an article on how to connect PHP and MySQL. In the end of this article there is a link to a demo which I created, it has a HTML form sans form tags 😛 just to demonstrate username validation.

AJAX Code

First design a basic HTML form with a <span> tag next to the username input box to display validation messages. The <span> tag should have an ID attribute so that it can be referenced in javascript.

<div>Username: <input type="text" maxlength="10" name="uname" id="uname" /><span id="status"></span></div>

I’m covering only the line which validates the username and not the form handling and other stuff. Paste the following code somewhere under the form.

<script type="text/javascript">
document.getElementById("uname").onblur = function() {
var xmlhttp;
var uname=document.getElementById("uname");
if (uname.value != "")
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("status").innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("GET","/uname_availability.php?uname="+encodeURIComponent(uname.value),true);
xmlhttp.send();
}
};
</script>

Lets dive deep into the code and understand its working.

document.getElementById("uname").onblur = function()

The first line triggers the entire function when the element with ID “uname” looses focus i.e. when the cursor goes inside the text box and then leaves it. The next two lines are variable declarations which need no explanation. Moving to the first “if” statement.

if (uname.value != "")

This line ensures validation is not unnecessarily performed if the text box is left empty. Now lets get into the heart of the code.

if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

These lines are used to create a HTTP request object. If statement is true on browsers IE7+, Firefox, Chrome, Opera, Safari the else loop is executed if the browser is IE5 or 6 and an ActiveX object is created.

xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("status").innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("GET","/uname_availability.php?uname="+encodeURIComponent(uname.value),true);
xmlhttp.send();

The xmlhttp.onreadystatechange is an event which is triggered after xmlhttp.send sends a request. The xmlhttp.open statement sends a GET request to the PHP URL mentioned and passes the username entered as a query string. If the server returns a status code of 200 it is matched by the “if” statement xmlhttp.status and the response text is placed in the innerHTML of the element with ID “status” (which is <span> tag in this case).

PHP Code

Now the PHP code has to GET this data match it with the database and print an answer. The following code will do just that.

<?php
$uname=$_REQUEST['uname'];
if(preg_match("/[^a-z0-9]/",$uname))
{
print "<span style=\"color:red;\">Username contains illegal charaters.</span>";
exit;
}
mysql_connect("localhost","Username","Password");
mysql_select_db("database_name");
$data=mysql_query("SELECT * FROM users where username='$uname'");
if(mysql_num_rows($data)>0)
{
print "<span style=\"color:red;\">Username already exists :(</span>";
}
else
{
print "<span style=\"color:green;\">Username is available :)</span>";
}
?>

See how it works on this demo page. Do post your comments and suggestions. Check these articles for more javascript validations.

Related posts:

web design category thumbnailJavascript Validation – Textbox Combobox Radiobutton Checkbox web design category thumbnailJavascript Validation with Regular Expressions php category thumbnailPHP Open Port Check Script web design category thumbnailJavascript Simple Slideshow connect php with mysql thumbnailConnect PHP with MySQL

Tags: ajax, javascript, php

Comments

  1. MiCR0 says

    May 22, 2013 at 4:50 pm

    $data=mysql_query("SELECT * FROM users where username='$uname'");

    This is open to MySQL SQL Injection.
    Should be

    $data=mysql_query("SELECT * FROM users where username='".mysql_real_escape_string($uname)."'");
    Reply
  2. dilip says

    February 21, 2014 at 10:03 pm

    i have tried your code for checking username availability but there is one issue according to my website as per your example it works fine but when i select existing user name from database it shows message like user name is exist but even if this message is shown when i click on submit button it stores data in database so i want to know how make validation that not allow user to store existing user name when he/she click on submit button.
    thanks

    Reply
    • Shayne says

      January 19, 2015 at 12:41 am

      Use something like:
      document.getElementById(‘submit’).disabled = true;
      This will disable the submit button. After checking whether it is available, you could enable it by changing ‘true’ to ‘false’.

      Reply
  3. Pavan says

    July 3, 2014 at 1:44 pm

    Thanq the code is very helpful.

    Reply
  4. GOKUL says

    August 7, 2014 at 2:04 pm

    thank you …

    Reply
  5. Danyal Fayyaz says

    December 27, 2015 at 4:17 pm

    You could use jquery for the ajax call its much simple. Anyway code is working perfect. Thanks Alot

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Get a wealth of information delivered to your inbox. Subscribe and never miss a single article.

  • Tutorials and howtos
  • Code, scripts and commands
  • Online Tools

* No spam, unsubscribe anytime

Hire Me

  • SSL installation and hardening (A+ on Qualys SSL test)
  • Apache & Nginx configuration
  • Email deliverability improvement (10/10 on Mail Tester & MailGenius)
  • WordPress customization, optimization and migration
  • and much more…

    Tools

    • DNS Lookup Tool
    • htdigest Generator Tool Online
    • htpasswd Generator Tool Online
    • HTTP Headers Lookup Tool
    • MD5 Encryption Tool
    • Open Port Check Tool
    • SHA-1 Encryption Tool
    • URL Encoding/Decoding Tool

    Nav

    • Home
    • About Me
    • Contact Me
    • Privacy Policy
    • Sitemap
    Vultr SSD VPS

    Creative Commons License
    Jesin's Blog by Jesin A is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
    Based on a work at websistent.com.