部分JS代码阻止表单提交和保存在数据库中

时间:2017-07-07 07:15:55

标签: javascript jquery

我在页面上有简单的表格

<form name="basicform" id="basicform" method="post" action="post.php" enctype="multipart/form-data" role="form">
    <div class="panel panel-primary setup-content" id="step-1">
        <div class="panel-heading">
             <h3 class="panel-title">Tell us about yourself</h3>
        </div>
        <div class="panel-body">
            <div class="form-group">
                <label class="control-label">Your Name *</label>
                <input maxlength="100" type="text" name="entry_name" required="required" class="form-control" placeholder="" />
            </div>              
            <button class="btn btn-primary nextBtn pull-right open1" type="button">Next</button>
        </div>
    </div>

    <div class="panel panel-primary setup-content" id="step-2">
        <div class="panel-heading">
             <h3 class="panel-title">Final Step!</h3>
        </div>
        <div class="panel-body">
            <button class="btn btn-success pull-right open2" type="submit" name="add" id="add">I agree. I’m ready to get my itinerary!</button>
            <img src="assets/images/spinner.gif" alt="" id="loader" style="display: none; width:32px;height:32px;">

        </div>
    </div>
</form>

这是JS(问题所在的部分)

// validate form on keyup and submit
var v = jQuery("#basicform").validate({
  rules: {},
  errorElement: "span",
  errorClass: "help-inline-error",
});    
$(".open1").click(function() {
  if (v.form()) {
    $(".frm").hide("fast");
    $("#sf2").show("slow");
  }
});

$(".open2").click(function() {
  if (v.form()) {
    $("#loader").show();
     setTimeout(function(){
       $("#basicform").html('<img src="assets/images/logo3.png" style="width:450px;height:250px;margin-left: 30%;"><h2>Awesome! </h2>');
     }, 1000);
    return false;
  }
});

这是我删除时保存在数据库中的部分。

// validate form on keyup and submit
var v = jQuery("#basicform").validate({
  rules: {},
  errorElement: "span",
  errorClass: "help-inline-error",
}); 

但如果我删除它,这部分就不再起作用了

$(".open2").click(function() {
  if (v.form()) {
    $("#loader").show();
     setTimeout(function(){
       $("#basicform").html('<img src="assets/images/logo3.png" style="width:450px;height:250px;margin-left: 30%;"><h2>Awesome! </h2>');
     }, 1000);
    return false;
  }
});
你能在这帮我吗?抱歉,我忘记提及当我删除验证部分并单击“下一步”按钮时,我在控制台中收到此错误

  

未捕获的ReferenceError:v未定义

这是因为if (v.form())如果我删除了v.并且只留下form()仍然无效

2 个答案:

答案 0 :(得分:0)

这是你的意思吗?

var v = jQuery("#basicform").validate({
  rules: {},
  errorElement: "span",
  errorClass: "help-inline-error",
});    
$(".open1").click(function() {

  if (v.form()) {
    $("#step-1").hide("fast");
    $("#step-2").show("slow");
  }
});

$(".open2").click(function() {
  if (v.form()) {
    $("#loader").show();
     setTimeout(function(){
       $("#basicform").html('<img src="assets/images/logo3.png" style="width:450px;height:250px;margin-left: 30%;"><h2>Awesome! </h2>');
     }, 1000);
    return false;
  }
});
.hidden{

  display:none;

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.js"></script>


<form name="basicform" id="basicform" method="post" action="post.php" enctype="multipart/form-data" role="form">
    <div class="panel panel-primary setup-content" id="step-1">
        <div class="panel-heading">
             <h3 class="panel-title">Tell us about yourself</h3>
        </div>
        <div class="panel-body">
            <div class="form-group">
                <label class="control-label">Your Name *</label>
                <input maxlength="100" type="text" name="entry_name" required="required" class="form-control" placeholder="" />
            </div>              
            <button class="btn btn-primary nextBtn pull-right open1" type="button">Next</button>
        </div>
    </div>

    <div class="panel panel-primary setup-content hidden" id="step-2">
        <div class="panel-heading">
             <h3 class="panel-title">Final Step!</h3>
        </div>
        <div class="panel-body">
            <button class="btn btn-success pull-right open2" type="submit" name="add" id="add">I agree. I’m ready to get my itinerary!</button>
            <img src="assets/images/spinner.gif" alt="" id="loader" style="display: none; width:32px;height:32px;">

        </div>
    </div>
</form>

答案 1 :(得分:0)

嗯,我的采掘方式有所不同。我希望这有帮助。下面是我的php:

 if ($app->nameLength($last_name) || $app->nameLength($first_name) || $app->nameLength($other_name) || $app->nameLength($ref_name)) {

    if ($app->nameValidation($last_name) || $app->nameValidation($first_name) || $app->nameValidation($other_name) || $app->nameValidation($ref_name)) {

        if ($app->emailValidation($email)) {

            $account->addUserEmail($email);

                if ($account->userExist($email)) {
                    $response['type'] = "error";
                    $response['msg'] = "The email address you have entered is already registered!";
                 }else{
                    if($userID = $account->create()) {
                        if ($member->newMember($userID)) {

                         $response['type'] = "success";

                        }

                    }
                }

            } else {
                $response['type'] ="error";
                $response['msg'] = 'Invalid email!, Please enter a valid Email';
            }

    } else {
        $response['type'] = "error";
        $response['msg'] = 'Name InValid, Please enter a valid Name';
    }
} else {
    $response['type'] = "error";
    $response['msg'] = 'Name must be more than 3 characters!';
}
}


header('Content-Type: application/json');

echo json_encode($response);

然后,当响应发送到ajax时,将发生以下情况:

 var v = $("#register-form").validate({

        rules: {
            last_name: {
                required: true,
                minlength: 3,
            },
            first_name: {
                required: true,
                minlength: 3,
            },
            other_name: {
                required: true
            },
            email: {
                required: true,
                email: true,
            },
            address: "required",
          },
        messages:
            {
                last_name: {
                    required: "Please enter your last name",
                    minlength: "LastName must be more than 2 characters!"
                },
                first_name: {
                    required: "Please enter your first name",
                    minlength: "FirstName must be more than 2 characters!"
                },
                other_name: "Please enter your other name",
                email: "Please enter a valid email",
                address: "Please enter your address",

            },
      //setting and styling errors
      errorElement: 'span',
      errorClass: 'invalid',
      errorPlacement: function(error, element) {
          if ( element.is(":radio"))
          {

              error.appendTo(element.parents('.custom-options'));
          }else if(element.is(":file")){
              error.insertAfter(".error-pd" );
          }
          else
          { // This is the default behavior
              return false;
          }
          // default
      },
        submitHandler: function () {
            //e.preventDefault();
            submitForm();
        }
    });

/* AJAX form submit function */
function submitForm(e){

   //e.preventDefault();

    var last_name = $("#last_name").val();
    var first_name = $("#first_name").val();
    var other_name = $("#other_name").val();
    var email = $("#email").val();
    var address = $("#address").val();



    var formData = {
        last_name: last_name,
        first_name: first_name,
        other_name: other_name,
        email: email,
        address: address,
        };

    $.ajax({
        type: 'POST',
        url: 'process.php',
        data: formData,
        success: function (data) {

            if (data.type === "success"){
                //$("#register-form").html(data.msg);
                return true;
         }


            console.log(data.type);
            $("#register-form")[0].reset();

        },
         error: function (error) {
             console.log(error);
         }
    })

}

// Binding next button on first step - Multi-Step form
$(".open1").click(function () {
    if (v.form()) {
        $(".frm").hide("fast");
        $("#sf2").show("slow");
    }
});
//$('form').on('submit', function (e) {

$("#do_reg").click(function (event){
  //event.preventDefault();
    if (v.form()) {
        $("#loader").show();
        setTimeout(function () {
            $("#register-form").html('<h2>Thanks for your time.</h2>');

        }, 1000);
        //return false;
    }
});
// Binding back button on second step
$(".back2").click(function () {
    $(".frm").hide("fast");
    $("#sf1").show("slow");
});

因此,PHP的任何响应都在data变量中,该变量可以通过data.type进行访问。

然后输入我的html代码:

 <form id="register-form" name="register-form" action="<?php echo $app->h("process.php");?>" method="POST">

                                  <div id="sf1" class="frm">
                             <div id="reg-error" class="le-error"></div>
                        <div class="form-group">
                            <div class="row">
                            <!-- Adding Columns -->
                            <div class="col-md-6 col-xs-12">
                            <label>Personal Information</label>
                            <input type="text" class="form-control" id="last_name" name="last_name" placeholder="Last Name">
                            <input type="text" class="form-control" id="first_name" name="first_name" placeholder="First Name">
                            <input type="text" class="form-control" id="other_name" name="other_name" placeholder="Other Names">
                            <input type="email" class="form-control" id="email" name="email" placeholder="E-mail">
                            <input type="text" class="form-control" id="address" name="address" placeholder="Address">
 <button class="btn btn-success open2" id="do_reg" name="submit" type="submit">Submit</button>

请记住,我的html比这更长。我只是简短地给出了基本的理解。如果您需要完整的内容以更好地理解它,我将为您提供...这对我有用,并通过ajax发送数据,并在同一页上显示“谢谢”。