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

时间:2018-02-22 17:23:58

标签: javascript php html ajax

所以我正在做一个功课,我想在用户输入时实时查看用户名。

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

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

请帮帮我:)。

以下是代码:

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>

checkUserRealTimeEx.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以及数据得到的值和它来自哪里:/如果你也可以向我解释那部分,我将非常非常感谢:)(

2 个答案:

答案 0 :(得分:1)

问题是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>

答案 1 :(得分:0)

您不能将同一文档用作ajax代码的接收器。您必须有一份单独的文件。

(见其他答案)[values not updated after an ajax response