在提交表单之前检查用户名是否可用

时间:2016-03-06 11:42:46

标签: javascript php ajax

我想检查是否在提交表单之前使用了用户名。

据我所知,我必须使用AJAX从我的数据库中获取数据。如何将用户名发送到PHP文件?

这是我的表格:



<form id="loginForm" action="register.php" method="post">
    <p>Register:</p>
    <p style="text-align: left;">Full name: <br><input type="text" name="name" required/></p>
    <p style="text-align: left;">Email: <br><input type="text" name="email" required/></p>

    //Username
    <p style="text-align: left;">Username: <br><input id="username" type="text" name="username" onkeyup="validateUsername(value);" required/></p>
    <span id="usernameError" style="display:none;border:1px solid red;">Username can only contain a-z, 0-9 and must be at least 6 characters loong</span>
    <span id="usernameTaken" style="display:none;border:1px solid red;">Username taken</span>

    <p style="text-align: left;">Password: <br><input type="password" name="password" required/></p>
    <input type="submit" value="Register">
</form>
&#13;
&#13;
&#13;

这是validateUsername()函数:

&#13;
&#13;
function validateUsername(username) {
    var re = /[a-zA-Z0-9]/;
    alert(username.length);
    if(re.test(username) && username.length > 5) {
        document.getElementById('username').style.backgroundColor = "green";
        document.getElementById('usernameError').style.display= "none";
        --error;
    } else {
        document.getElementById('username').style.backgroundColor = "red";
        document.getElementById('usernameError').style.display= "block";
        ++error;
    }
    //here i want to check if the user name is taken
}
&#13;
&#13;
&#13;

如果使用了用户名,我想显示&#39; usernameTaken&#39;跨度。 否则,我想隐藏它。

这是用于检查用户名是否已存在于数据库中的PHP文件:

&#13;
&#13;
<?php
session_start();
define('DB_NAME', 'madsanker_dk_db');
define('DB_USER', 'madsanker_dk');
define('DB_PASSWORD', 'MyPassword');
define('DB_HOST', 'mysql43.unoeuro.com');

$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);

if (!$link) {
    die('Could not connect: ' .mysqli_error());
}

$db_selected = mysqli_select_db( $link, DB_NAME);

if (!$db_selected) {
    die('Could not connect: ' .mysqli_connect_error());
}

$username = //The username;
$username = mysqli_real_escape_string($link,$username);

$sql = "SELECT * FROM mainLogin WHERE username = '$username'";

$result = mysqli_query($link, $sql);
$count = mysqli_num_rows($result);

if($count == 0) {
    //if the username is NOT taken
    return true;
} else {
    //if the username IS taken
    return false;
}
mysqli_close($link);
?>
&#13;
&#13;
&#13;

这是怎么做到的?

2 个答案:

答案 0 :(得分:1)

JS - JQUERY AJAX

$.ajax({ 
    url: 'register.php', data: {action: 'isUserNameTaken', params: [username]},
    type: 'post',
    success: function(data) {
        //Do Something
    }
});

<强> PHP

&#13;
&#13;
<?php
function isUserNameTaken($username) {
    //Do Something;
}

if(!empty($_POST['action'])) {
    $action = $_POST['action'];
    switch($action) {
        case 'isUserNameTaken':
            $username = '';

            if(!empty($_POST['params'])) {
                $username = $_POST['params'][0];
            }

            isUserNameTaken($username);

            break;
    }
}
?>
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

你可以这样做: 在客户端:

function validateUsername(){
   if(//test username input for length...) {
   $.ajax({  
         type: 'POST',  
         url: 'validate.php', 
         data: { username: username },
         success: function(response) {
              if(response==0){
                 //username is valid
               }
              elseif(response==1){
               //username is already taken
              }
              elseif(response==2){
                //connection failed 
              }

         }
   });
  }
  else{
     //display "username is too short" error
  }

}

validate.php:

<?php
session_start();
define('DB_NAME', 'madsanker_dk_db');
define('DB_USER', 'madsanker_dk');
define('DB_PASSWORD', 'MyPassword');
define('DB_HOST', 'mysql43.unoeuro.com');

$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);

if (!$link) {
  die('Could not connect: ' .mysqli_error());
   echo json_encode(2);
}
 else{
   $db_selected = mysqli_select_db( $link, DB_NAME);

   if (!$db_selected) {
      die('Could not connect: ' .mysqli_connect_error());
       echo json_encode(2);
    }
    else{
       $username = $_POST["username"];
       $username = mysqli_real_escape_string($link,$username);

       $sql = "SELECT * FROM mainLogin WHERE username = '$username'";

       $result = mysqli_query($link, $sql);

       $count = mysqli_num_rows($result);
       if($count == 0) {
         //if the username is NOT taken
         echo json_encode(0); 
       }else {
          //if the username IS taken
             echo json_encode(1);
        }
        mysqli_close($link);
    }


 }

?>

你也可以通过jquery中的onkeyup函数调用它来使这个函数使用validateUsername,这样每次用户在输入字段中键入内容时,都会检查用户名....