简体   繁体   中英

Real time username check with $.ajax

So I am doing a homework, in which I would like to check the username in real time, as the user types it.

It is working correctly, only when I change the content of the HTML element to "username available or not", it also displays the whole site one again there, but much smaller.

So actually in the cell ehere I want to display "available" or "not available" the whole page appears again. The proble must be the SUCCESS part of the $.ajax function, but I can not see why.

Please help me :)

Here are the codes:

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";
}

?>

So as I said I am pretty sure the proble will be with the data as input value in the success part, but I don't really understand where I pass the value back to the register.php and what value data gets and where it gets from :/ If you could also explain that part to me, I would be very-very thankful :)

The issue is that the form on register.php submits to the register.php, which contains both the registration form and the logic to process the form. When you submit a form to a page (which is what you are doing here), the HTML of that page will be displayed unless you tell it to do otherwise. The cleanest way to handle this would be to have a separate page to handle the registration (as suggested by gibberish in his answer).

However, you could still have the form submit to itself as long as you hide the HTML content when registration has occurred and show some feedback instead (eg "Registration successsful!"). The PHP code at the top of register.php knows whether or not the form was submitted and whether or not the registration was successful. You can leverage that by setting a variable when the registration was successful (eg $registered=true ) and use that variable to decide whether you want to display the registration form or a success message. Again, this isn't as 'clean' as two separate pages, but it is a quick workaround to solve your issue.

This updated version of register.php does what I am describing:

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

You cannot use the same document as the receiver for your ajax code. You must have a separate document.

(See this other answer)[ values not updated after an ajax response

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM