javascript - 使用 $.ajax 进行实时用户名检查

标签 javascript php html ajax

所以我正在做一项作业,我想在用户键入用户名时实时检查用户名。

它工作正常,只有当我将 HTML 元素的内容更改为“用户名是否可用”时,它还会再次显示整个网站,但要小得多。

所以实际上在单元格中我想显示“可用”或“不可用”,整个页面再次出现。问题一定是 $.ajax 函数的 SUCCESS 部分,但我不明白为什么。

请帮助我:)

代码如下:

注册.php:

<?php

define("HOSTNAME","localhost");
define("USERNAME","root");
define("PASSWORD","");
define("DATABASE","authentication");

//connect database
$conn = new mysqli(HOSTNAME,USERNAME,PASSWORD,DATABASE);
if($conn->connect_error){
    die("Connection failed: " .$conn->connect_error);
}
if(isset($_POST['register_btn'])){
    session_start();
    $username = $conn->real_escape_string($_POST['username']);
    $email = $conn->real_escape_string($_POST['email']);
    $password = $conn->real_escape_string($_POST['password']);
    $password2 = $conn->real_escape_string($_POST['password2']);

    if($password == $password2 && strlen($password) > 5 && strlen($username) > 5 && strlen($email) > 5){
        //create user
        $password = md5($password); //hash password before storing for security purposes
        $sql = "INSERT INTO users(username, email, password) VALUES('$username', '$email', '$password')";
        if($conn->query($sql)){
            echo "New record created successfully";
            $_SESSION['message'] = "You are now logged in";
            $_SESSION['username'] = $username;
            header("location: home.php"); //redirect to home page
        }
        else{
            echo "Error: " . $sql . "<br>" . $conn->error;
        }
    }
    else{
        //failed
        $_SESSION['message'] = "The two passwords do not match";
    }
}

?>



<!DOCTYPE html>
<html>
<head>
    <title>Register</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<svg viewBox="0 0 500 37">
    <path id="curve" d="M 105 33 q 150 -20 300 0" />
    <text width="500">
      <textPath xlink:href="#curve">az én oldalam lesz</textPath>
    </text>
</svg>
<div class="header">
    <h1>Register</h1>
</div>

<script type="text/javascript">

function checkUserRealTime(val){
    $.ajax({
        type:"POST",                        //type of the request to make
        url:"checkUserRealTimeEx.php",      //server the request should be sent
        data:"username="+val,               //the data to send to the server
        success: function(data){            //the function to be called if the request succeeds
            $("#msg").html(data);
        }

    });
}

</script>

<form method="post" action="register.php">
    <table>
        <tr>
            <td>Username:</td>
            <td><input type="text" name="username" class="textInput" placeholder="username" onkeyup="checkUserRealTime(this.value)"></td>
        </tr>
        <tr>
            <td></td>
            <td><p id="msg"></p></td>
        <tr>
            <td>Email:</td>
            <td><input type="email" name="email" placeholder="E-mail address" class="textInput"></td>
        </tr>
        <tr>
            <td>Password:</td>
            <td><input type="password" name="password" placeholder="Password" class="textInput"></td>
        </tr>
        <tr>
            <td>Password again:</td>
            <td><input type="password" name="password2" placeholder="Password again" class="textInput"></td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit" name="register_btn" class="Register"></td>
        </tr>
    </table>
</form>
</body>
</html>

检查UserRealTimeEx.php:

<?php

require "register.php";

$username = $conn->real_escape_string($_POST["username"]);

$query = "SELECT * FROM users WHERE username='".$username."'";
$results = $conn->query($query);
$numRows = $results->num_rows;

if($numRows > 0){
    echo "Username not available";
}
else{
    echo "Username available";
}

?>

所以正如我所说,我很确定问题将在于成功部分中的数据作为输入值,但我真的不明白将值传递回 register.php 的位置以及数据获得的值和它从哪里来:/如果你也能向我解释那部分,我将非常非常感激:)

最佳答案

问题在于,register.php 上的表单提交到 register.php,其中包含注册表单和处理表单的逻辑。当您向页面提交表单时(这就是您在此处所做的操作),除非您告诉它否则,否则将显示该页面的 HTML。处理这个问题的最干净的方法是有一个单独的页面来处理注册(正如他的回答中的胡言乱语所建议的那样)。

但是,只要您在注册时隐藏 HTML 内容并显示一些反馈(例如“注册成功!”),您仍然可以让表单自行提交。 register.php 顶部的 PHP 代码知道表单是否提交以及注册是否成功。您可以通过在注册成功时设置一个变量(例如 $registered=true)来利用这一点,并使用该变量来决定是否要显示注册表单或成功消息。同样,这并不像两个单独的页面那么“干净”,但它是解决您的问题的快速解决方法。

这个更新版本的 register.php 实现了我所描述的功能:

<?php

define("HOSTNAME","localhost");
define("USERNAME","root");
define("PASSWORD","");
define("DATABASE","authentication");

$registered = false;
$username = '';

//connect database
$conn = new mysqli(HOSTNAME,USERNAME,PASSWORD,DATABASE);
if($conn->connect_error){
    die("Connection failed: " .$conn->connect_error);
}
if(isset($_POST['register_btn'])){
    session_start();
    $username = $conn->real_escape_string($_POST['username']);
    $email = $conn->real_escape_string($_POST['email']);
    $password = $conn->real_escape_string($_POST['password']);
    $password2 = $conn->real_escape_string($_POST['password2']);

    if($password == $password2 && strlen($password) > 5 && strlen($username) > 5 && strlen($email) > 5){
        //create user
        $password = md5($password); //hash password before storing for security purposes
        $sql = "INSERT INTO users(username, email, password) VALUES('$username', '$email', '$password')";
        if($conn->query($sql)){
            echo "New record created successfully";
            $_SESSION['message'] = "You are now logged in";
            $_SESSION['username'] = $username;
            header("location: home.php"); //redirect to home page
            $registered = true; // Set the flag indicating that registration was successful
        }
        else{
            echo "Error: " . $sql . "<br>" . $conn->error;
        }
    }
    else{
        //failed
        $_SESSION['message'] = "The two passwords do not match";
    }
}

?>



<!DOCTYPE html>
<html>
<head>
    <title>Register</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<svg viewBox="0 0 500 37">
    <path id="curve" d="M 105 33 q 150 -20 300 0" />
    <text width="500">
      <textPath xlink:href="#curve">az én oldalam lesz</textPath>
    </text>
</svg>
<div class="header">
    <h1>Register</h1>
</div>

<script type="text/javascript">

function checkUserRealTime(val){
    $.ajax({
        type:"POST",                        //type of the request to make
        url:"checkUserRealTimeEx.php",      //server the request should be sent
        data:"username="+val,               //the data to send to the server
        success: function(data){            //the function to be called if the request succeeds
            $("#msg").html(data);
        }

    });
}

</script>

<?php
  if (!$registered) {
?>

<form method="post" action="register.php">
    <table>
        <tr>
            <td>Username:</td>
            <td><input type="text" name="username" class="textInput" placeholder="username" onkeyup="checkUserRealTime(this.value)"></td>
        </tr>
        <tr>
            <td></td>
            <td><p id="msg"></p></td>
        <tr>
            <td>Email:</td>
            <td><input type="email" name="email" placeholder="E-mail address" class="textInput"></td>
        </tr>
        <tr>
            <td>Password:</td>
            <td><input type="password" name="password" placeholder="Password" class="textInput"></td>
        </tr>
        <tr>
            <td>Password again:</td>
            <td><input type="password" name="password2" placeholder="Password again" class="textInput"></td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit" name="register_btn" class="Register"></td>
        </tr>
    </table>
</form>

<?php
    } else {
?>

<div>Registration Successful for user <?= $username ?></div>

<?php
}
?>

</body>
</html>

关于javascript - 使用 $.ajax 进行实时用户名检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48933668/

相关文章:

javascript - JQuery 选择器问题——如何找到目标 = _blank 的所有 HREF?

javascript - 如何仅在选择第一个下拉列表后启用第二个下拉列表?

javascript - AngularJS - 模糊+改变?

javascript - d3 中具有不同翻转 Action 的多个多边形

php - 我如何在学校使用我的 Git

php - CN_match 已弃用,取而代之的是 peer_name

javascript - onchange 下拉列表将参数添加到输入框中的 url

php - 如果没有元描述,我如何使用 p 标签的 20 个字符

html - 输入选项(单选框和复选框)有带图标的按钮

html - 边框增加在悬停过渡时移动 div