Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php JQuery验证-仅在验证完成时提交表单_Php_Jquery_Validation - Fatal编程技术网

Php JQuery验证-仅在验证完成时提交表单

Php JQuery验证-仅在验证完成时提交表单,php,jquery,validation,Php,Jquery,Validation,我正在处理一个联系人表单,它使用jquery验证表单以确保输入的所有数据都是正确的。当我点击submit按钮时,一切正常-验证错误消息与确认消息一起出现,说明消息已发送。因此,虽然所有字段都不完整,但基本上是发送表单 我只希望在正确填写所有字段后提交表单 我已经在下面包含了我的代码 //验证联系人表单 $(函数(){ $('.contactusform')。验证({ 规则:{ 姓名:{ 必填项:true }, 电话号码:{ 要求:正确, 数字:对 }, 电邮:{ 要求:正确, 电子邮件:真的

我正在处理一个联系人表单,它使用jquery验证表单以确保输入的所有数据都是正确的。当我点击submit按钮时,一切正常-验证错误消息与确认消息一起出现,说明消息已发送。因此,虽然所有字段都不完整,但基本上是发送表单

我只希望在正确填写所有字段后提交表单

我已经在下面包含了我的代码


//验证联系人表单
$(函数(){
$('.contactusform')。验证({
规则:{
姓名:{
必填项:true
},
电话号码:{
要求:正确,
数字:对
},
电邮:{
要求:正确,
电子邮件:真的
},
城镇:{
必填项:true
},
设备:{
必填项:true
},
信息:{
必填项:true
},
},
信息:{
姓名:{
必填:“请输入您的全名。”
},
电话号码:{
必填:“请输入您的电话号码。”
},
电邮:{
必填:“请输入您的电子邮件地址。”
},
城镇:{
必填:“请进入您的城镇。”
},
设备:{
必需:“请选择您的设备。”
},
信息:{
必填:“请输入您的信息。”
},
},
})
});
$(文档).ready(函数(){
$('.contactusform').validate();
//获取提交按钮ID。不要在表单内部使用。请在表单外部使用按钮。
$(“#提交2”)。单击(函数()
{
//获取表单ID
$(“#消息”).submit(函数(e)
{
//添加加载图像以代替返回的结果
$(“#简单消息”).html(“发送…”);
//将所有提交的字段序列化/合并到一个数组中
var postData=$(this.serializeArray();
//设置基于url的操作类型
var formURL=$(this.attr(“操作”);
//设置ajax参数
$.ajax(
{
url:formURL,
类型:“POST”,
数据:postData,
成功:函数(数据、文本状态、jqXHR)
{
$(“#simple msg”).html(“感谢您的请求-我们将很快联系!

”); }, 错误:函数(jqXHR、textStatus、errorshown) { $(“#简单消息”).html(“消息发送失败。请重试!

”); } }); e、 preventDefault();//停止默认操作 e、 解除绑定(); }); $(“#消息”).submit();//提交表单 }); });
在调用ajax之前,请检查表单是否有效

使用此新代码更新您的代码:

if($('.contactusform').valid()){
        $.ajax(
            {
                url : formURL,
                type: "POST",
                data : postData,
                success:function(data, textStatus, jqXHR) 
                {
                    $("#simple-msg").html('<p>Thanks for your request - we will be in touch soon!</p>');

                },
                error: function(jqXHR, textStatus, errorThrown) 
                {
                    $("#simple-msg").html('<p>Message failed to send. Please try again!</p>');
                }
            });
}
if($('.contactusform').valid()){
$.ajax(
{
url:formURL,
类型:“POST”,
数据:postData,
成功:函数(数据、文本状态、jqXHR)
{
$(“#simple msg”).html(“感谢您的请求-我们将很快联系!

”); }, 错误:函数(jqXHR、textStatus、errorshown) { $(“#简单消息”).html(“消息发送失败。请重试!

”); } }); }
要解决您的问题,请注意以下几点:

  • 将两个脚本合并为一个,因为将它们放在不同的标记中是完全没有意义的
  • 使用表单的
    ID
    className
    ,但是最好使用
    ID
    。[对于答案,我假设
    .contactusform
    #contactusform
    引用DOM中的相同元素]
  • 不需要第二次调用
    .validate()
    方法(因此必须删除)。[它可能会用传入的验证规则对象覆盖
    .validate()
    方法的第一次调用。]
  • //抓取提交按钮ID。不要在表单内使用。在窗体外部使用按钮。
    $(“#submit2”)。单击(函数()

    --为什么不在表单中使用一个带有
    type='button'
    的按钮,这样可以防止表单被提交,这样您就可以执行AJAX调用了

  • 现在,要在表单的
    submit
    事件上注册处理程序,请将代码的最后一部分替换为以下内容:

    $("#contactusform").submit(function(e) //Note the registration of the submit event on the form and NOT a button
        {
            var theForm = this;    // reference to the form that raised the event
            // add a loading image in place of your returning outcome
            $("#simple-msg").html("Sending...");
    
            // serialize/combine all submitted fields into an array
            var postData = $(this).serializeArray();
    
            // set url based of action
            var formURL = $(this).attr("action");
    
            // set ajax parameters
            $.ajax(
            {
                url : formURL,
                type: "POST",
                data : postData,
                success:function(data, textStatus, jqXHR) 
                {
                    $("#simple-msg").html('<p>Thanks for your request - we will be in touch soon!</p>');
    
                },
                error: function(jqXHR, textStatus, errorThrown) 
                {
                    $("#simple-msg").html('<p>Message failed to send. Please try again!</p>');
                }
            });
            e.preventDefault(); //STOP default action -- Is ok to be here, although changing the form submission button's type to `button` will do the same trick
            //e.unbind();   // Not necessary
        });
    
        //$("#message").submit(); //SUBMIT FORM --- No need for this again, not sure if '#message' is a form, but either way, by clicking the form submission button, you'll be triggering the submit event on the form.
    });
    

    @Ahmad Baktash Hayeri的答案几乎涵盖了所有方面,所以这个答案的目的是使用插件,当使用插件时,为什么不利用它,让它为您完成所有的艰苦工作

    我建议完全删除第二个脚本,使用
    submitHandler函数
    ,处理Ajax方法和其中的所有其他请求

    检查以下脚本,您有不必要的逗号和缺少的

    $(document).ready(function () {
        $('.contactusform').validate({
            rules: {
                name: {
                    required: true
                },
                telno: {
                    required: true,
                    number: true
                },
                email: {
                    required: true,
                    email: true
                },
                town: {
                    required: true
                },
                device: {
                    required: true
                },
                message: {
                    required: true
                }, //<---unnecessary, remove it
            },
            messages: {
                name: {
                    required: "Please enter your full name."
                },
                telno: {
                    required: "Please enter your phone number."
                },
                email: {
                    required: "Please enter your email address."
                },
                town: {
                    required: "Please enter your town."
                },
                device: {
                    required: "Please select your device."
                },
                message: {
                    required: "Please enter your message."
                }, //<---unnecessary, remove it
    
            },
            //Submit Handler Function
            submitHandler: function (form) {
            // add a loading image in place of your returning outcome
            $("#simple-msg").html("Sending...");
            // serialize/combine all submitted fields into an array
            var postData = $(this).serializeArray();
            // set url based of action
            var formURL = $(this).attr("action");
            $.ajax({
                    type: "POST",
                    url: formURL,
                    data: postData,
                    success:function(data, textStatus, jqXHR) {
                       $("#simple-msg").html('<p>Thanks for your request - we will be in touch soon!</p>');
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                       $("#simple-msg").html('<p>Message failed to send. Please try again!</p>');
                    }
                });
            }
        }); //<----missing ; in original code
    });
    
    e、 g如果您想在Ajax成功函数后重置表单并禁用按钮

    success:function(data, textStatus, jqXHR) {
       $("#simple-msg").html('<p>Thanks for your request - we will be in touch soon!</p>');
       $(form)[0].reset();
       $('#theSubmitButton').attr("disabled", true);
    },
    
    编辑:

    OP后来添加了表单,因此需要在HTML中进行更改

    移动到
    中,并将
    类型='按钮'
    更改为
    类型='submit'

    <form name='message' id='message' class="contactusform" enctype="multipart/form-data" action="<?=admin_url()?>admin-post.php">
    <?php
    if(isset($_SESSION['message'])){
     echo $_SESSION['message'];
     unset($_SESSION['message']);
     }
    ?>
         <input type="hidden" name="action" value="add_foobar">
         <input type="hidden" name="data" value="foobarid">
         <label>Full Name:</label>
         <input type="text" name="name" value="" required="">
         <label>Phone Number:</label>
         <input type"=text" name="telno" id="telno">
         <label>Email Address:</label>
         <input type="email" name="email" value="" required="">
         <label>Town:</label>
         <input type"=text" name="town" value="" required="">
         <label>Device:</label>
         <select name="device" value="" required="">
            <option selected="selected" value=""></option>
            <option value="Not Sure">Not Sure</option>
            ....Rest of the option attributes
            <option value="iPod Touch">iPod Touch</option>
        </select>
        <label>Message:</label><textarea name="message" cols="30" rows="4" value="" required=""></textarea>
        <input class="submit2" type='submit' id='submit' value='Send Message' />
    </form>
    <div id='simple-msg'></div>
    

    您需要将该Ajax请求放入submitHandler
    submitHandler:function(form){将Ajax调用放在这里,删除第二个脚本,并在submitHandler中执行您想要执行的所有操作}
    我可以给你不同的建议。如果你agree@Joshua,你也能分享你表格的html吗?@Shehary和Dinanath Thakur-谢谢你的建议-
    success:function(data, textStatus, jqXHR) {
       $("#simple-msg").html('<p>Thanks for your request - we will be in touch soon!</p>');
       $(form)[0].reset();
       $('#theSubmitButton').attr("disabled", true);
    },
    
    onkeyup: function( element, event ) {
       this.checkForm();
        if (this.valid()) { // checks form for validity
            $('#theSubmitButton').attr("disabled", false); //Button enable if all fields valid
        } else {
            $('#theSubmitButton').attr("disabled", true); //button will disbale if any field not valid
        }
    },
    
    <form name='message' id='message' class="contactusform" enctype="multipart/form-data" action="<?=admin_url()?>admin-post.php">
    <?php
    if(isset($_SESSION['message'])){
     echo $_SESSION['message'];
     unset($_SESSION['message']);
     }
    ?>
         <input type="hidden" name="action" value="add_foobar">
         <input type="hidden" name="data" value="foobarid">
         <label>Full Name:</label>
         <input type="text" name="name" value="" required="">
         <label>Phone Number:</label>
         <input type"=text" name="telno" id="telno">
         <label>Email Address:</label>
         <input type="email" name="email" value="" required="">
         <label>Town:</label>
         <input type"=text" name="town" value="" required="">
         <label>Device:</label>
         <select name="device" value="" required="">
            <option selected="selected" value=""></option>
            <option value="Not Sure">Not Sure</option>
            ....Rest of the option attributes
            <option value="iPod Touch">iPod Touch</option>
        </select>
        <label>Message:</label><textarea name="message" cols="30" rows="4" value="" required=""></textarea>
        <input class="submit2" type='submit' id='submit' value='Send Message' />
    </form>
    <div id='simple-msg'></div>