ajax - 执行php脚本和数据验证时出错 - 如何解决?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (41)

我为我的网站制作了注册表格。然后,我创建了PHP脚本,该脚本验证并将用户数据插入到数据库中,并且它完美地运行。然后,我尝试进行AJAX验证,这将在HTML元素上应用样式,并在发生错误时显示错误消息。我按照一些教程,从Stack Overflow读取答案和解决方案,但由于某种原因,它不起作用。单击“提交”按钮时,没有任何反应。

这是我的代码:

HTML

<form id="signupForm" action="./includes/signup.script.php" method="POST">
   <div id="emptyFields" class="inputErrorMessage">
      <p>You must fill all fields!</p>
   </div>
   <div class="form-group">
      <label for="formGroupExampleInput">First name</label>
      <input id="firstName" type="text" name="firstName" class="form-control formFieldBO">
      <div id="firstNameChar" class="inputErrorMessage">
         <p>First name must contain letters only.</p>
      </div>
      <div id="firstNameLength" class="inputErrorMessage">
         <p>First name must contain at least 2 characters.</p>
      </div>
   </div>
   <div class="form-group">
      <label for="formGroupExampleInput">Last name</label>
      <input id="lastName" type="text" name="lastName" class="form-control formFieldBO">
      <div id="lastNameChar" class="inputErrorMessage">
         <p>Last name must contain letters only.</p>
      </div>
      <div id="lastNameLenght" class="inputErrorMessage">
         <p>Last name must contain at least 2 characters.</p>
      </div>
   </div>
   <div class="form-group">
      <label for="formGroupExampleInput">E-mail</label>
      <input id="email" type="email" name="email" class="form-control formFieldBO">
      <div id="emailValid" class="inputErrorMessage">
         <p>Please, enter e-mail in valid form.</p>
      </div>
   </div>
   <div class="form-group">
      <label for="formGroupExampleInput">Password</label>
      <input id="password" type="password" name="password" class="form-control formFieldBO">
      <div id="passwordChar" class="inputErrorMessage">
         <p>Password must contain at least 6 characters.</p>
      </div>
   </div>
   <div class="form-group">
      <label for="formGroupExampleInput">Confirm Password</label>
      <input id="confirmPassword" type="password" name="confirmPassword" class="form-control formFieldBO">
      <div id="passwordConfirm" class="inputErrorMessage">
         <p>Confirmed password does not match.</p>
      </div>
   </div>
   <div class="form-group">
      <label for="formGroupExampleInput">Country</label>
      <select id="inputState" name="country" class="form-control formFieldBO">
         <option value="" disabled selected>Select country</option>
         <option value="AFG">Afghanistan</option>
      </select>
      <div id="countryChoose" class="inputErrorMessage">
         <p>Please, choose your country.</p>
      </div>
   </div>
   <div class="buttonBO">
      <button type="submit" name="submit" class="btn btn-success">Submit</button>
   </div>
</form>

JQuery脚本

$(document).ready(function() {
    $("#signupForm").submit(function(event) {
        event.preventDefault();
        /*
        var firstName = $("#firstName").val();
        var lastName = $("#lastName").val();
        var email = $("#email").val();
        var password = $("#password").val();
        var confirmPassword = $("#confirmPassword").val();
        var country = $("#inputState").val();
        */
        var url = "includes/signup.script.php";
        var formData = $(this).serialize();
        $.ajax({
            type: "POST",
            url: url,
            data: formData
        });
    });
});

PHP和JQuery

<?php
if (isset($_POST['submit']))
    {
    include_once "dbconn.script.php";

    $firstName = mysqli_real_escape_string($conn, $_POST['firstName']);
    $lastName = mysqli_real_escape_string($conn, $_POST['lastName']);
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $password = mysqli_real_escape_string($conn, $_POST['password']);
    $confirmPassword = mysqli_real_escape_string($conn, $_POST['confirmPassword']);
    $user_role = 1;
    $country = mysqli_real_escape_string($conn, $_POST['country']);
    $errorEmpty = false;
    $errorFirstNameChar = false;
    $errorFirstNameNo = false;
    $errorLastNameChar = false;
    $errorLastNameNo = false;
    $errorEmail = false;
    $errorPasswordChar = false;
    $errorPasswordMatch = false;
    $errorCountry = false;
    // Error handlers
    // Check for empty fields
    if (empty($firstName) || empty($lastName) || empty($email) || empty($password) || empty($confirmPassword))
        {
        header("Location: ../registration.php?registration=empty");
        $errorEmpty = true;
        exit();
        }
      else
        {
        // Check if input FIRST NAME characters are valid
        if (!preg_match("/^[a-zA-Z]*$/", $firstName))
            {
            header("Location: ../registration.php?registration=firstinvalidchar");
            $errorFirstNameChar = true;
            exit();
            }
          else
            {
            // Check if number of FIRST NAME characters is valid
            if (strlen($firstName) < 2)
                {
                header("Location: ../registration.php?registration=invalid1");
                $errorFirstNameNo = true;
                exit();
                }
              else
                {
                // Check if input LAST NAME characters are valid
                if (!preg_match("/^[a-zA-Z]*$/", $lastName))
                    {
                    header("Location: ../registration.php?registration=lastinvalidchar");
                    $errorLastNameChar = true;
                    exit();
                    }
                  else
                    {
                    // Check if number of LAST NAME characters is valid
                    if (strlen($lastName) < 2)
                        {
                        header("Location: ../registration.php?registration=invalid2");
                        $errorLastNameNo = true;
                        exit();
                        }
                      else
                        {
                        // Check if EMAIL is valid
                        if (!filter_var($email, FILTER_VALIDATE_EMAIL))
                            {
                            header("Location: ../registration.php?registration=invalidemail");
                            $errorEmail = true;
                            exit();
                            }
                          else
                            {
                            // PREPARED STATEMENT
                            // Create template
                            $sql = "SELECT e_mail FROM hieroglyphicus_users WHERE e_mail=?;";
                            // Create prepared statement
                            $stmt = mysqli_stmt_init($conn);
                            // Prepare the prepared statement
                            if (!mysqli_stmt_prepare($stmt, $sql))
                                {
                                echo "SQL statement failed!";
                                }
                              else
                                {
                                // Bind parameters to the placeholder
                                mysqli_stmt_bind_param($stmt, "s", $email);
                                // Run parameters inside database
                                mysqli_stmt_execute($stmt);
                                $result = mysqli_stmt_get_result($stmt);
                                $resultCheck = mysqli_num_rows($result);
                                if ($resultCheck > 0)
                                    {
                                    header("Location: ../registration.php?registration=userexists");
                                    exit();
                                    }
                                  else
                                    {
                                    // Check if password number of characters is valid
                                    if (strlen($password) < 6)
                                        {
                                        header("Location: ../registration.php?registration=invalidemaicharno");
                                        $errorPasswordChar = true;
                                        exit();
                                        }
                                      else
                                        {
                                        // Check if passwords match
                                        if ($password != $confirmPassword)
                                            {
                                            header("Location: ../registration.php?registration=mismatchedpass");
                                            $errorPasswordMatch = true;
                                            exit();
                                            }
                                          else
                                            {
                                            if ($country == "")
                                                {
                                                header("Location: ../registration.php?registration=nocountry");
                                                $errorCountry = true;
                                                exit();
                                                }
                                              else
                                                {
                                                // Hashing passwords
                                                $hashedPwd = password_hash($password, PASSWORD_DEFAULT);
                                                // Insert a user into the database
                                                // PREPARED STATEMENT
                                                // Create template
                                                $sql = "INSERT INTO hieroglyphicus_users (first_name, last_name, e_mail, user_pw, user_role, country) 
                                                            VALUES (?, ?, ?, ?, ?, ?);";
                                                // Create prepared statement
                                                $stmt = mysqli_stmt_init($conn);
                                                // Prepare the prepared statement
                                                if (!mysqli_stmt_prepare($stmt, $sql))
                                                    {
                                                    echo "SQL statement failed!";
                                                    }
                                                  else
                                                    {
                                                    // Bind parameters to the placeholder
                                                    mysqli_stmt_bind_param($stmt, "ssssis", $firstName, $lastName, $email, $hashedPwd, $user_role, $country);
                                                    // Run parameters inside database
                                                    mysqli_stmt_execute($stmt);
                                                    header("Location: ../registration.php?registration=success");
                                                    exit();
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
  else
    {
    header("Location: ../registration.php");
    exit();
    }
?>

<script>
        $("#firstName, #lastName, #email, #password, #confirmPassword, #country").removeClass("formFieldBOError").addClass("formFieldBO");
        $(".inputErrorMessage").hide();

        var errorEmpty = "<?php echo $errorEmpty; ?>";
        var errorFirstNameChar = "<?php echo $errorNameFirstChar; ?>";
        var errorFirstNameNo = "<?php echo $errorFirstNameNo; ?>";
        var errorLastNameChar = "<?php echo $errorNameLastChar; ?>";
        var errorLastNameNo = "<?php echo $errorLastNameNo; ?>";
        var errorEmail = "<?php echo $errorEmail; ?>";
        var errorPasswordChar = "<?php echo $errorPasswordChar; ?>";
        var errorPasswordMatch = "<?php echo $errorPasswordMatch; ?>";
        var errorCountry = "<?php echo $errorCountry; ?>";

        if (errorEmpty == true) {
            $("#emptyFields").show();
            $("#signupForm :input:not(:button):not(:select)").removeClass("formFieldBO").addClass("formFieldBOError");
        }
        if (errorFirstNameChar == true) {
            $("#firstNameChar").show();
            $("#firstName").removeClass("formFieldBO").addClass("formFieldBOError");
        }
        if (errorFirstNameNo == true) {
            $("#firstNameChar").show();
            $("#firstName").removeClass("formFieldBO").addClass("formFieldBOError");
        }
        if (errorLastNameChar == true) {
            $("#lastNameChar").show();
            $("#lastName").removeClass("formFieldBO").addClass("formFieldBOError");
        }
        if (errorLastNameNo == true) {
            $("#lastNameChar").show();
            $("#lastName").removeClass("formFieldBO").addClass("formFieldBOError");
        }
        if (errorEmail == true) {
            $("#emailValid").show();
            $("#email").removeClass("formFieldBO").addClass("formFieldBOError");
        }
        if (errorPasswordChar == true) {
            $("#passwordChar").show();
            $("#password").removeClass("formFieldBO").addClass("formFieldBOError");
        }
        if (errorPasswordMatch == true) {
            $("#passwordConfirm").show();
            $("#confirmPassword").removeClass("formFieldBO").addClass("formFieldBOError");
        }
        if (errorCountry == true) {
            $("#countryChoose").show();
            $("#inputState").removeClass("formFieldBO").addClass("formFieldBOError");
        }
        if (errorEmpty == false && errorFirstNameChar == false && errorFirstNameNo == false && errorLastNameChar == false && errorLastNameNo == false && errorEmail == false && errorPasswordChar == false && errorPasswordMatch == false && errorCountry == false) {
            $("#firstName, #lastName, #email, #password, #confirmPassword, #country").val("");
        }

</script>

我无法发现问题或错误。任何帮助都非常感谢!

提问于
用户回答回答于
  1. $(“#signupForm”)。on('submit',function(){
  2. 将所有JQuery验证代码放在此函数下。
  3. 更改按钮类型=“提交”到输入类型=“提交”。

让我们看看这是否可以解决您的问题。

扫码关注云+社区

领取腾讯云代金券