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

£可爱£侵袭症+ 提交于 2021-02-07 03:16:49

问题


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...


回答1:


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.




回答2:


You need to pass $username variable correctly.

Single quotes php vars are treated as plain strings and variables aren't evaluated.

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

OR

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



回答3:


soo I spent some time looking for, and testing answer, so I should, posted my results and what working for me..

html, or php form:

<script src="http://code.jquery.com/jquery-3.3.1.js"></script>
<form class="a16" action="register.php" method="POST" autocomplete="on">
                                    <label for="userName" class=" ">Użytkownik:</label>

<input type="text" name="userName" placeholder="Username" id="userName1" onBlur="checkAvailability()">

      <span id="user-availability-status"></span> 
<p><img src="LoaderIcon.gif" id="loaderIcon" style="display:none" /></p>

 <script type="text/javascript">     

function checkAvailability() {
$("#loaderIcon").show();
jQuery.ajax({
url: "proceser.php",
data:'userName='+$("#userName1").val(),
type: "POST",
success:function(data){
$("#user-availability-status").html(data);
$("#loaderIcon").hide();
},
error:function (){}
});
}
</script>

and proceser.php :

<?php
 include 'dbconnect.php';   //standard datebase local connection..

 if(isset($_POST['userName']) && $_POST['userName']!="") {
     if ($stmt = $con->prepare('SELECT userName FROM users WHERE userName = ?')) {
         $stmt->bind_param('s', $_POST['userName']);
         $stmt->execute();
         $stmt->store_result();
         $numRows = $stmt->num_rows;
         if ($numRows > 0) {
             echo "<span class=''> Username Not Available.</span>";
         } else {
             echo "<span class=''> Username Available.</span>";
         }
     }
 }
$con->close();
ob_end_flush();

?>


Thank you!:)


来源:https://stackoverflow.com/questions/35823166/check-if-username-exists-in-real-time-through-ajax-in-php-with-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!