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…

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

   <script type="text/javascript">

     $(document).ready(function(){
        $("#username").change(function(){
             $("#message").html("<img src='images/loader.gif' /> checking...");


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

          $.ajax({
                type:"post",
                url:"check.php",
                data:"username =" + username,
                    success:function(data){
                    if(data==0){
                        $("#message").html("<img src='images/tick.png' /><span style='font-size:13px; color: black'> Username available</span>");
                    }
                    else{
                        $("#message").html("<img src='images/err.png' /><span style=font-size:13px; color: red'> Username already taken</span>");
                    }
                }
             });

        });

     });

   </script>
   </head>

   <body>

   <table>
    <tr>
          <td>Username</td>
          <td>:</td>
          <td><input type="text" name="username" id="username"/><td>
            <td id="message"><td>
    </tr>

    <tr>
          <td>Password</td>
          <td>:</td>
          <td><input type="text" name="password" id="password" /><td>
    </tr>
   </table>
   </body>
   </html>

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

<?php

$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;

  mysqli_close($con);

  ?>

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…

Answer

Send your data in javascript using jQuery like this:

$.post( "check.php", { user: $("#username").val() }, function (data){
  if(data=='1'){
   //do 1
  }
  elseif(data=='0'){
    //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 *