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

Javascript 使用$.ajax进行实时用户名检查,javascript,php,html,ajax,Javascript,Php,Html,Ajax,因此,我正在做一个家庭作业,我想在用户键入用户名时实时检查用户名 它工作正常,只有当我将HTML元素的内容更改为“username available or not”时,它才会再次显示整个站点,但要小得多 因此,实际上在单元格e中,我想显示“可用”或“不可用”,整个页面再次出现。问题一定是$.ajax函数的成功部分,但我不明白为什么 请帮帮我:) 代码如下: Register.php: <?php define("HOSTNAME","localhost"); define("USERN

因此,我正在做一个家庭作业,我想在用户键入用户名时实时检查用户名

它工作正常,只有当我将HTML元素的内容更改为“username available or not”时,它才会再次显示整个站点,但要小得多

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

请帮帮我:)

代码如下:

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

您不能使用与ajax代码接收者相同的文档。你必须有一份单独的文件


(参见另一个答案)[

问题是register.php上的表单提交到register.php,其中包含注册表单和处理表单的逻辑,该页面的HTML将显示,除非您告诉它,否则将显示。处理此问题的最干净方法是使用单独的页面来处理注册(正如胡言乱语在其回答中所建议的)

但是,只要在注册时隐藏HTML内容并显示一些反馈(例如“注册成功!”),您仍然可以让表单提交到自己。位于register顶部的PHP代码。PHP知道表单是否已提交以及注册是否成功。注册成功时,您可以通过设置变量来利用这一点(例如,
$registed=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>

我真的不明白你的意思,抱歉,我应该在单独的文档中有什么。我在register.php中有ajax代码,在checkUserRealTimeEx.php中执行php代码。我没有得到你链接的其他答案。嗨-只是跟进一下。如果Benjamin Ray的答案帮助你解决了问题,请选择它作为CHOen answer(单击答案左上角的复选标记)关闭问题。谢谢!
<?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>