具有jQuery验证和AJAX的Bootstrap联系表 [英] Bootstrap Contact Form with jQuery Validation and AJAX

查看:71
本文介绍了具有jQuery验证和AJAX的Bootstrap联系表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的引导联系表单,我正在尝试使用AJAX和jQuery验证来实现.我觉得我已经很接近了,但是有些事情我不能完全正确地工作.表单根据输入进行验证(理想情况下,我希望将电话号码验证为数字;但是,我是联系表单验证的新手),但是即使答案不正确,联系表单仍会发送.此外,提交表单后,成功框将始终弹出...如果表单填写不正确,我希望表单不发送,并显示错误框来代替成功框.此外,电子邮件通过消息的正文发送,但没有任何变量被发送出去.因此,我的邮件正文如下所示:
姓名:
电子邮件:
电话:
消息:

每个变量后面都没有变量.

I have a simple bootstrap contact form that I'm trying to implement with AJAX and jQuery validation. I feel like I'm pretty close but there are a few things that I can't get to work quite right. The forms validate according to input (ideally I'd like the phone number to be validated as digits; however, I'm new to contact form validation), but the contact form will still send even if the answers are not correct. In addition, the success box will always pop up after the form submits ... I'd like the form to not send if it is filled out incorrectly, and an error box to appear instead of the success. In addition, the email sends through the body of the message, but none of the variables get sent over. So the body of my message looks like:
Name:
Email:
Phone:
Message:

With no variable appear after each.

我知道这可能很简单,但是我是新来进行表单验证的人,我一生都无法弄清楚.

I know this may be something simple but I'm very new to form validation and I can't figure it out for the life of me.

以下是表单的HTML:

Here's the HTML for the form:

<div class="form-group wow fadeInRight" data-wow-delay="1s">
  <div class="controls">
    <div class="input-group">
      <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
      <input type="text" class="form-control" id="name" name="name" placeholder="Name" />
    </div>
  </div>
</div>

<div class="form-group wow fadeInRight" data-wow-delay="1.1s">
  <div class="controls">
    <div class="input-group">
      <span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
      <input type="text" class="form-control" id="email" name="email" placeholder="Email" />
    </div>
  </div>  
</div>

<div class="form-group wow fadeInRight" data-wow-delay="1.2s">
  <div class="controls">
    <div class="input-group">
      <span class="input-group-addon"><i class="glyphicon glyphicon-phone"></i></span>
      <input type="text" class="form-control" id="phone" name="phone" placeholder="Phone" />
    </div>
  </div>
</div>

<div class="form-group wow fadeInRight" data-wow-delay="1.3s">
  <div class="controls">
    <div class="input-group">
      <span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
      <textarea name="message" class="form-control " rows="4" cols="78" placeholder="Enter your message here."></textarea>
    </div>
  </div>
</div>

<div id="success"></div>
<div class="row wow fadeInUp" data-wow-delay="1.3s">
  <div class="form-group col-xs-12">
    <div class="contact-btns">
      <input type="submit" class="submit-button" value="Submit" name="submit">
      <input type="reset" class="clear-buttom" value="Clear" name="clear">
    </div>
  </div>
</div>

</form>

这是PHP:

$status = array(
    'type' => 'success',
    'message' => 'Email sent!'
);

$val = $_POST['val'];
$toemail = 'myemail@gmail.com';
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$msg = $_POST['message'];

$subject = 'Thelliotgroup Information Request';

$headers = "From: Thelliotgroup Website :: " . $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

$message = "<b>Name: </b>" . $name . "<br>";
$message .='<b>Email: </b>' . $email . "<br>";
$message .='<b>Phone: </b>' . $phone . "<br>";
$message .='<b>Message: </b>' . $msg;

$success = mail($toemail, $subject, $message, $headers);

echo json_encode($status);
die

这是AJAX和jQuery:

Here's the AJAX and jQuery:

var form = $('.contact');
form.submit(function () {
    $this = $(this);
    $.post($(this).attr('action'), function (data) {
        $this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
    }, 'json');
    return false;
});


$.validator.setDefaults({
    submitHandler: function (form) {
        $.ajax({
            type: "POST",
            url: "email.php",
            data: {'val': $(".contact").serializeJSON()}
        }).done(function (data) {
            alert(data);
        });
    }
});

$(".contact").validate(
        {rules:
                    {name: "required",
                        email: {required: true, email: true},
                        phone: "required",
                        message: {required: true, maxlength: 300
                        }},
            errorClass: "error",
            highlight: function (label) {
                $(label).closest('.form-group').removeClass('has-success').addClass('has-error');
            },
            success: function (label) {
                label
                        //.text('Seems Perfect!').addClass('valid')
                        .closest('.form-group').addClass('has-success');
            }
        });

我真的很感谢你们能给我任何帮助,以使它正常工作.

I'd really appreciate any help you guys could give me to get this working properly.

修改 这是新的jQuery和AJAX代码:

Edit Here's the new jQuery and AJAX code:

$(document).ready(function() {
var form = $(this); 
var post_url = form.attr('action'); 
$('.contact').validate({ 
    rules: {
        name: {
            rangelength: [2,40], 
            required: true
        },
        email: {
            rangelength: [2,40], 
            email: true,
            required: true
        },
        phone: {
            rangelength: [7,10],
            required: true
        },
        message: {
            minlength: 30,
            required: true
        },
        errorClass:"error",
        highlight: function(label) {
            $(label).closest('.form-group').removeClass('has-success').addClass('has-error');
        },

        success: function(label) {
            label
            .closest('.form-group').addClass('has-success');
        }
    },
    submitHandler: function(form) { 
        $.ajax({
            type: 'POST',
            url: 'email.php',
            data: $(form).serialize(),
            success: function(msg) {
                $('.sent').fadeIn().fadeOut(5000);
            }
        });            
        return false; 
    }                  
});                    

});

现在,我只需要弄清楚如何做到这一点:

Now I just need to figure out how to make it so that:

<div class="status alert alert-success" style="display: none"></div>

位于表单正上方的位置,将在提交表单后淡入. 我无法使它正常工作.

Which is located directly above the form, will fade in once the form is submitted. I can't get it to work.

谢谢, 布伦南

推荐答案

我不明白为什么您要在jQuery submit处理函数中执行.post()(ajax),而您却同时拥有插件submitHandler函数内部的.ajax().我不明白你为什么要两次使用ajax?

I do not understand why you're doing a .post() (ajax) inside of a jQuery submit handler function while at the exact same time you have .ajax() inside of the plugin's submitHandler function. I don't get it. Why are you using ajax twice?

我认为最好删除整个功能...

I think it's best that you remove this entire function...

form.submit(function () {
    $this = $(this);
    $.post($(this).attr('action'), function(data) {
        $this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
    },'json');
    return false;
});

因为它干扰了插件的submitHandler功能.

Because it is interfering with the plugin's submitHandler function.

当表单有效时,使用submitHandler在按钮click上触发代码. 这是任何ajax所属的地方.

Use the submitHandler to fire code upon the button click when the form is valid. This is where any ajax would belong.

编辑:

您已将errorClasshighlightsuccess 放入了rules选项...

You've put errorClass, highlight and success inside the rules option...

rules: {
    name: {
        ....
    },
    email: {
        ....
    },
    phone: {
        ....
    },
    message: {
        ....
    },
    errorClass:"error",
    highlight: function(label) {
        ....        
    },
    success: function(label) {
        ....
    }
},

这是错误的. errorClasshighlightsuccessrulessubmitHandler选项的兄弟姐妹.

This is wrong. errorClass, highlight and success are siblings of the rules and submitHandler options.

此外,在使用highlight时,最好同时使用unhighlight来撤消对highlight所做的任何操作.

Also, when using highlight, it's best to use unhighlight along with it to undo whatever you did with highlight.

rules: {
    // only your rules here
},
errorClass:"error",
highlight: function(element) {
    $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
},
unhighlight: function(element) {
    $(element).closest('.form-group').addClass('has-success').removeClass('has-error');
},
submitHandler: function(form) { 
    $.ajax({
        // your options
    });            
    return false; 
}


用于清除Ajax success选项中的表单...


For clearing out the form within the Ajax success option...

$('#myform').validate().resetForm(); // reset validation
form[0].reset();                     // clear out the form data             

这篇关于具有jQuery验证和AJAX的Bootstrap联系表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆