Ajax Username Validation with PHP and MySQL
Database and table
First create a database in mysql and create a table called members in it.
CREATE DATABASE books;CREATE TABLE members (id INT(20) NOT NULL AUTO_INCREMENT, username VARCHAR(100)); |
Insert some dummy values.
INSERT INTO members (username) VALUES("anand.roshan");... |
Example
HTML Markup
input type="text" name="username" id="username" placeholder="Enter Username">div id="availability">div> |
We need a text input box and a div to show the result, with suitable ids.
jQuery
$(document).ready(function () { $("#username").blur(function () { var username = $(this).val(); if (username == '') { $("#availability").html(""); } else{ $.ajax({ url: "validation.php?uname="+username }).done(function( data ) { $("#availability").html(data); }); } });}); |
After including the jQuery library insert the above code inside of your head tag
We used a function called .blur()
Whenever the input box with the id of “username” looses its focus, the jQuery code will send an ajax request to validation.php.
For this tutorial, we’ve used GET method but you can use POST method as well.
validation.php
$db_user = "YOUR_DB_USER";$db_password = "YOUR_DB_PASSWORD";$db_name = "YOUR_DB_NAME";$db_host = "YOUR_DB_HOST";//connecting to mysql database$con = new mysqli($db_host, $db_user, $db_password, $db_name);//prints error message if connection is not successfulif ($con −> connect_error > 0) { die('Unable to connect to database [' . $con −> connect_error . ']');}//Gets username value from the URL$uname = $_GET['uname'];//Checks if the username is available or not$query = "SELECT username FROM members WHERE username = '$uname'";$result = mysqli_query($con, $query);//Prints the resultif (mysqli_num_rows($result)<1) { echo " class='green'>Available";}else{ echo " class='red'>Not available";} |
Basically it sends the username to validation.php if it is not empty
We are trying to select the username from members table where the username is equal to the value entered in text box.
If the result returns one or more rows, then the username is not available otherwise it is availabe.

