check if username exists in real-time through AJAX in php with mysql
<p>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.<br><br>
This is my <strong>username.php</strong> where the user actually enters the username &amp; password and from where the <strong>check.php</strong> is triggered... <br><br></p>

<pre><code>&lt;html&gt;
&lt;head&gt;
   &lt;script type="text/javascript" src="js/jquery-1.7.1.min.js"&gt;&lt;/script&gt;

   &lt;script type="text/javascript"&gt;

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


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

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

        });

     });

   &lt;/script&gt;
   &lt;/head&gt;

   &lt;body&gt;

   &lt;table&gt;
    &lt;tr&gt;
          &lt;td&gt;Username&lt;/td&gt;
          &lt;td&gt;:&lt;/td&gt;
          &lt;td&gt;&lt;input type="text" name="username" id="username"/&gt;&lt;td&gt;
            &lt;td id="message"&gt;&lt;td&gt;
    &lt;/tr&gt;

    &lt;tr&gt;
          &lt;td&gt;Password&lt;/td&gt;
          &lt;td&gt;:&lt;/td&gt;
          &lt;td&gt;&lt;input type="text" name="password" id="password" /&gt;&lt;td&gt;
    &lt;/tr&gt;
   &lt;/table&gt;
   &lt;/body&gt;
   &lt;/html&gt;
</code></pre>

<p>This is the <strong>check.php</strong> where the username is checked in the database.<br><br></p>

<pre><code>&lt;?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);

  ?&gt;
</code></pre>

<p>Now the <strong>check.php</strong> is working fine (which I checked through executing it alone and it returns <strong>1</strong> on finding the username and <strong>vice versa</strong>)<br>
However when I execute the <strong>username.php</strong> <em>it always returns <strong>Username already taken</em></strong>. It seems it actually does not look in the database at all where actually there is no such username. <br>
<br>
Any kind of help will be much appreciated...</p>