doushang1880 2018-06-20 18:49
浏览 84

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

I made a Signup form for my website. Then, I created PHP script which validates and insert user data into the database and it works perfectly. Then, I tried to make AJAX validation which will apply styles on the HTML elements and show error messages if an error occurs. I followed some tutorials, read answers and solutions from Stack Overflow, but for some reason, it doesn't work. When I click Submit button, nothing happens.

This is my code:

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 script

$(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>

I cannot spot the problem or error. Any help is highly appreciated!

  • 写回答

1条回答 默认 最新

  • donglin9068 2018-06-21 00:15
    关注
    1. $("#signupForm").on('submit', function(){

    2. Put all the JQuery validation codes under this function .

    3. Change button type="submit" to input type="submit" .

    Let's see if this can solve your problems .

    评论

报告相同问题?

悬赏问题

  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗