php - 带有红色错误消息的表单验证不起作用(php、ajax、jquery 和 mysql)

标签 php jquery html mysql ajax

好吧,兄弟们,我对有关表单验证的通知的外观有疑问。我将问题与 php 代码中的一些问题相关联,例如由变量 $errors 和 $data 定义的数组。我真的不明白它们的用法。或者它可能与 jQuery 代码中的某处有关。
这些代码基于我在互联网上找到的网站教程。另外,我在 Ajax 和 jQuery 领域没有经验。也许你可以解决这个简单的问题。我什至附加了注册页面的屏幕截图以及处理 php 与数据库连接的下一页。

This is the sign up page called join_form.php

This is the processing page called register2.php

这是html代码:

<html>
  <head>
   <title>
    This is the form page
  </title>
  </head>
  <body>
    <center>
      <br>
      <br>
      <img src="images/quintz.png" width="156" height="44" alt=""/>
      <br>
      <br>
      Register now
      <br>
      <br>
      <div id="bugado">
        <form id="ajax_form" method="post" action="register2.php">
          <div id="usertype-group" class="form-group">
            <label for="usertype">
              You're a 
              </label>

              <select name="usertype" class="form-control">
                <option value="native speaker">
                  Native speaker
                </option>
                <option value="non-native speaker">
                  Non-native speaker
                </option>
              </select>
              <br>
              <!-- errors will go here -->
              </div>
              <div id="username-group" class="form-group">
                <label for="username">
                  Create username: 
                </label>

                <input name="username" type="text" maxlength="30" class="form-control" placeholder="Username">
                <br>
              </div>
              <div id="email-group" class="form-group">
                <label for="email">
                  Email: 
                </label>

                <input name="email" type="text" maxlength="50" class="form-control" placeholder="Email">
                <br>
                <!-- errors will go here -->
              </div>
              <div id="password-group" class="form-group">
                <label for="password">
                  Create password: 
                </label>

                <input type="password" name="password" class="form-control" placeholder="Password">
                <br>
              </div>
              <label>
                Confirm password: 
              </label>

              <input type="password" name="confirm_password" class="form-control" placeholder="Password again">
              <br>
              <button type="submit" name="submit" class="btn btn-success">
                Submit
              </button>
              <span class="fa fa-arrow-right">
              </span>
              <br>
              <input name="reset" type="reset" value="Reset">
              </form>
              </div>
          </center>
      </body>
</html>

这是 jQuery 代码:

 <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.js"></script>
 <script language="javascript">
    $(document).ready(function() {

    // process the form
    $('#ajax_form').submit(function(event) {

        $('.form-group').removeClass('has-error'); // remove the error class
        $('.help-block').remove(); // remove the error text

        // get the form data
        // there are many ways to get this data using jQuery (you can use the class or id also)
        var formData = {
            'usertype'               : $('select[name="usertype"]').val(),
            'username'              : $('input[name="username"]').val(),
            'email'             : $('input[name="email"]').val(),
            'password'  : $('input[name="password"]').val()
        };

        // process the form
        $.ajax({
            type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
            url         : $(form).attr('action'), // the url where we want to POST
            data        : formData, // our data object
            dataType    : 'json', // what type of data do we expect back from the server
            encode      : true
        })
            // using the done promise callback
            .done(function(data) {

                // log data to the console so we can see
                console.log(data); 

                // here we will handle errors and validation messages
                if ( ! data.success) {

                    // handle errors for usertype ---------------
                    if (data.errors.usertype) {
                        $('#usertype-group').addClass('has-error'); // add the error class to show red select
                        $('#usertype-group').append('<div class="help-block">' + data.errors.usertype + '</div>'); // add the actual error message under our select
                    }

                    // handle errors for username ---------------
                    if (data.errors.username) {
                        $('#username-group').addClass('has-error'); // add the error class to show red input
                        $('#username-group').append('<div class="help-block">' + data.errors.username + '</div>'); // add the actual error message under our input
                    }

                    // handle errors for email ---------------
                    if (data.errors.email) {
                        $('#email-group').addClass('has-error'); // add the error class to show red input
                        $('#email-group').append('<div class="help-block">' + data.errors.email + '</div>'); // add the actual error message under our input
                    }

                    // handle errors for superhero alias ---------------
                    if (data.errors.password) {
                        $('#password-group').addClass('has-error'); // add the error class to show red input
                        $('#password-group').append('<div class="help-block">' + data.errors.password + '</div>'); // add the actual error message under our input
                    }

                } else {

                    // ALL GOOD! just show the success message!
                    $('#ajax_form').append('<div class="alert alert-success">' + data.message + '</div>');

                    // usually after form submission, you'll want to redirect
            // window.location = '/thank-you'; // redirect a user to another page
            alert('success'); // for now we'll just alert the user

                }
            })

            // using the fail promise callback
            .fail(function(data) {

                // show any errors
                // best to remove for production
                console.log(data);
            });

        // stop the form from submitting the normal way and refreshing the page
        event.preventDefault();
    });

});
</script>

这是 php 代码:

    <?php
    include 'db.php';

     $errors         = array();      // array to hold validation errors
     $data           = array();      // array to pass back data

     //Searching for identical usernames
     $search = mysql_query("SELECT * FROM natspeaker WHERE username = '".$_POST['username']."'");
     $count = mysql_num_rows($search);

     $search2 = mysql_query("SELECT * FROM nonnatspeaker WHERE username = '".$_POST['username']."'");
     $count2 = mysql_num_rows($search2);

     //Searching for identical emails
     $search3 = mysql_query("SELECT * FROM natspeaker WHERE email = '".$_POST['email']."'");
     $count3 = mysql_num_rows($search3);

     $search4 = mysql_query("SELECT * FROM nonnatspeaker WHERE email = '".$_POST['email']."'");
     $count4 = mysql_num_rows($search4);

     //if( isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD']=='POST' ) {
     if(isset($_POST)){
     //USERTYPE
     if(empty($_POST['usertype'])) { 
        $errors['usertype'] = "Please select if you are a native or a non-native speaker.<br>";
            }

     //USERNAME
     if (empty($_POST['username'])) {
        $errors['username'] = "Username is missing<br>";
            }else{//this "else" can be deleted

     /*this can be deleted in case of trouble*/if ( $count == 1 OR $count2 == 1) {
        $errors['username'] .= "Username already exists in our database. Choose another one<br>";
            }
            }//this bracket can be deleted.
     //EMAIL
     if (empty($_POST['email'])) {
        $errors['email'] = "Email is missing<br>";
            }else{//this "else" can be deleted

      if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $_POST['email'])) {
        $errors['email'] = "Invalid email<br>";
            }

       if ( $count3 == 1 OR $count4 == 1) {
        $errors['email'] = "Email already exists in our database. It seems you have an account yet.<br>";
            }
            }//this bracket can be deleted.

      //PASSWORD
      if (empty($_POST['password'])) {
        $errors['password'] = "Password is missing.<br>";
            }else{//this "else" can be deleted

      if (strlen($_POST['password']) < 6) {
        $errors['password'] = "Password too short<br>";
            }
            }//this bracket can be deleted.


        // return a response ===========================================================

       // if there are any errors in our errors array, return a success boolean of false
      if ( ! empty($errors)) {

        // if there are items in our errors array, return those errors
        $data['success'] = false;
        $data['errors']  = $errors; 
        //if(count($_SESSION['errors']) > 0){
        //This is for ajax requests:
        if( isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD']=='POST' ) {
            //if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&  strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])== 'xmlhttprequest') {//something is wrong with this
                header('Content-type: application/json');
                echo "Ajax request is working.";
                echo json_encode($data);//now this iss working
                exit;
             }
           //This is when Javascript is turned off:
           echo "<br><br><br><center><div style=\"font-size:50;\">something is wrong or your Javascript is turned off. Ajax request is not working</div></center><br><br>";//delete
           echo $data;//delete
           //foreach($_SESSION['errors'] as $key => $value){
          //echo "<li>" . $value . "</li>";
           //}
           //echo "</ul>";exit;
    }else{
    // if there are no errors process our form, then return a message

        // DO ALL YOUR FORM PROCESSING HERE
        // THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)
if ( $_POST['usertype'] == "native speaker") { 
      $register = mysql_query("INSERT INTO natspeaker(username, email, password, time1, usertype)
       VALUES ('".$_POST['username']."','".$_POST['email']."', '".$_POST['password']."', now(), '".$_POST['usertype']."')") or die (mysql_error());
        }elseif ( $_POST['usertype'] == "non-native speaker"){
         $register = mysql_query("INSERT INTO nonnatspeaker(username, email, password, time1, usertype)
        VALUES ('".$_POST['username']."', '".$_POST['email']."', '".$_POST['password']."', now(), '".$_POST['usertype']."')") or die (mysql_error());
         }

      // Let's mail the user!
      $subject = "Your Membership at Quintz!";
      $message = "Hi, ".$_POST['username'].",
      Thank you for registering at our website, http://www.quintz.club!

      You have registered as a ".$_POST['usertype'].".
      You are two steps away from logging in and accessing our exclusive members area.

      To activate your membership, please click here: http://www.quintz.club/activate.php

      Once you activate your membership, you will be able to login.

      And please do not forget to complete your profile.
      Thanks!
      The Webmaster

      This is an automated response, please do not reply!";

      mail($_POST['email'], $subject, $message, "From: Quintz Webmaster<support@quintz.club>\nX-Mailer: PHP/" . phpversion());

      // show a message of success and provide a true success variable
        $data['success'] = true;
        $data['message'] = 'Your account has been created successfully. Go to your email address and activate your account.';
        echo "successful register!";//delete
   }
}
//}
// return all our data to an AJAX call
//this works
//echo json_encode($data);//delete
?>

总之,我只是想阻止用户使用数据库中已经存在的用户名注册,或者使用无效的电子邮件,甚至缺少信息(空白字段),并在同一页面中返回那些红色通知join_form.php。用户只能进入register2.php,如果所有信息都被批准传递到数据库,最后显示“注册成功!”的信息。在此页面上并向用户发送电子邮件。就是这样!

最佳答案

我认为你需要回到开始。您的 HTML 显然不合格,并且您的 PHP 代码已经.. 过时了..

检查您的代码正在做什么,从 HTML 开始,然后使用 jQuery 处理表单,其中输出只是 true 或失败的表单字段的 ID,或类似的东西。

只是一些快速的事情;

  • titlehead 里面,而不是在它之上
  • mysql_query 已过时,请尝试使用 mysqli_query 或它的 OOP 变体
  • 必要时进行计数,如果整个表单都是空的,就没有理由让 mysql 服务器出现故障
  • 使用 OOP mysqli,您可以执行 $s = $mysqli->query('SELECT [..]'); 然后 if($s->num_rows > 0 ) 而不是创建一个新的计数变量,使用相同的方式来验证用户是否存在用于登录,然后仅使用 $r = $s->fetch_assoc() 来获取用户的详细信息。
  • 不要获取值,而是尝试使用 $('#form').serialize() 将它们全部写入一个数组,然后将其写入

简而言之,回到起点,从头开始并使用更新的教程。

关于php - 带有红色错误消息的表单验证不起作用(php、ajax、jquery 和 mysql),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33601212/

相关文章:

php - 尝试在确认中显示数据时,我不断收到未定义的消息

Jquery 第二次 Click Fire 事件第一次丢失

jquery - IE11 的 CORS 请求

html - 使用 bootstrap 3 调整图像周围的文本

php - 我是否应该将 ENT_QUOTES 与 htmlspecialchars 一起使用

php - 使用有限的内存处理来自 mysql 的大型结果集

javascript - Laravel 和隐藏输入

php - 通过 href 元素链接 li>a

javascript - 将 HTML5 Canvas 转换为 IMG 元素

c# - ASP.NET 控件中的安全 HTML