check if username exists in real-time through AJAX in php with mysql

I am working on a project in php/MySQL that requires me to check the username in real-time means as the user inputs the username.

This is my username.php where the user actually enters the username & password and from where the check.php is triggered…

   <script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>

   <script type="text/javascript">

             $("#message").html("<img src='images/loader.gif' /> checking...");

        var username = $("#username").val();

                data:"username =" + username,
                        $("#message").html("<img src='images/tick.png' /><span style='font-size:13px; color: black'> Username available</span>");
                        $("#message").html("<img src='images/err.png' /><span style=font-size:13px; color: red'> Username already taken</span>");





          <td><input type="text" name="username" id="username"/><td>
            <td id="message"><td>

          <td><input type="text" name="password" id="password" /><td>

This is the check.php where the username is checked in the database.


$con = mysqli_connect("localhost", "root", "hilbi", "userdb");

if (mysqli_connect_errno())

  echo "Failed to connect to MySQL: " . mysqli_connect_error();


  // $username = $_POST["username"];

  $username = 'hilbi';

  $query = mysqli_query($con,"SELECT * FROM users WHERE username =   '$username' ");

  $find = mysqli_num_rows($query);

  echo $find;



Now the check.php is working fine (which I checked through executing it alone and it returns 1 on finding the username and vice versa)
However when I execute the username.php it always returns Username already taken. It seems it actually does not look in the database at all where actually there is no such username.

Any kind of help will be much appreciated…


Send your data in javascript using jQuery like this:

$.post( "check.php", { user: $("#username").val() }, function (data){
   //do 1
    //do 0

In your check.php get username like this

//some basic validation
if(!isset($_POST['user'] || empty($_POST['user']))
   echo '0'; exit();

$username = trim($_POST['user']); 

For this to work properly you check.php must return either 1 or 0, do not echo mysql errors there or whatsoever. if any error occur, just echo 0.

Leave a Reply

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