如何使用JQuery和Ajax验证表单字段并将表单数据发布到服务器?

时间:2015-01-28 10:38:39

标签: javascript jquery ajax jquery-validate

我正在尝试验证表单字段,如名称(不能为空),Email_id(必须有效),移动(必须有效)。填写完所有信息后,我必须将此信息发送到服务器,并将响应重定向到不同的页面。 这里没有任何工作

my form.html

<form class="form-horizontal" id="scheduleLaterForm" name="scheduleLaterForm">
    <div class="col-lg-8">      
        <div class="fieldgroup">
            <label class="col-lg-3 control-label" for="userName">Name:<font
                style="color: red;">*</font></label>
            <div class="col-lg-9">
                <input style=" height: 30px;" class="form-control" id="userName" name="userName"
                    placeholder="Full Name" value="" type="text" required>
            </div>
        </div>

        <div class="fieldgroup">
            <label for="email" class="col-lg-3 control-label">Email:<font
                style="color: red;">*</font></label>
            <div class="col-lg-9">
                <input style="height: 30px;" class="form-control" name="email"
                    id="email" placeholder="you@example.com" value=""
                    type="text" required>
            </div>
        </div>

        <div class="fieldgroup">
            <label for="userContactNumber" class="col-lg-3 control-label">Mobile:<font
                style="color: red;">*</font></label>
            <div class="col-lg-9">
                <input style="height: 30px; width:100%;" class="form-control" id="userContactNumber"
                    name="userContactNumber" placeholder="Mobile Number"
                    onkeypress="enableKeys(event);" maxlength="10" type="text" required>
            </div>
        </div>

        <div class="fieldgroup">
            <label class="col-lg-3 control-label"></label>
                <div class="col-lg-7">
                    <input type="submit" value="Register" id="btnBooking" class="submit">
                </div>
        </div>
    </div>                                  
</form>
用于验证表单和发送数据的

脚本

 <script>
    $(document).ready(function(){
        $("#scheduleLaterForm").validate({
            rules: {
                userName: "required",                           
                email: {
                    required: true,
                    email: true
                },                                              
                userContactNumber: "required"                       
            },
            messages: {
                userName: "Please enter your Name",
                userContactNumber: "Please enter your Mobile number",                           
                email: "Please enter a valid email address",                                           
            },
            submitHandler: function(form) {
                // get values from textboxs 
                var uName = $('#userName').val();
                var mailId = $('#addressemailId').val();
                var mobNum = $('#userContactNumber').val();

                $.ajax({
                    url:"http://localhost/services/bookService4Homes.php",
                    type:"GET",
                    dataType:"json",
                    data:{type:"booking",Name:uName, Email:mailId, Mob_Num:mobNum },
                    //type: should be same in server code, otherwise code will not run
                    ContentType:"application/json",
                    success: function(response){
                         alert("success");
                        //alert(JSON.stringify(response));
                    },
                    error: function(err){
                         alert("fail");
                        //alert(JSON.stringify(err));
                    }
                });
                return false; // block regular submit
            }
        });
    });
</script> 

Php代码

<?php
header('Access-Control-Allow-Origin: *');//Should work in Cross Domaim ajax Calling request
mysql_connect("localhost","root","root");
mysql_select_db("service4homes");
if(isset($_GET['type']))
{
    if($_GET['type']=="booking"){
        $name = $_GET ['Name'];
        $mobile = $_GET ['Mob_Num'];
        $mail = $_GET ['Email'];    

        $query1 = "insert into customer(cust_name, cust_mobile, cust_email) values('$name','$mobile','$mail')";
        $result1=mysql_query($query1);
    }
}
else{
    echo "Invalid format";
}
?>

1 个答案:

答案 0 :(得分:0)

  • 您不需要外部click处理程序,因为该插件会自动捕获clicktype="submit")并阻止提交。

  • input button需要formtype="submit",否则该插件根本不会被触发。

    < / LI>
  • .ajax方法的form.submit范围内submitHandler时,您无法拥有外部.validate()功能。这意味着当您的点击处理程序尝试使用ajax时,插件会尝试提交表单。它们都不能同时工作。 As per docs, any ajax belongs inside the submitHandler, and it's "the right place to submit a form via Ajax after it is validated"

  • 您不需要检查表单的有效性,因为当您使用内置的submitHandler时,这也会自动完成。

  • jQuery4U代码只不过是复杂的垃圾;一切都可以大大简化。除了给寻求指导的人带来更多混淆之外,它没有用处。它来自Sam Deering的一个流行的,但解释不佳的在线演示/教程,它与许多地方相连。

    $(document).ready(function(){
    
        $("#register-form").validate({
            rules: {
                userName: "required",                           
                email: {
                    required: true,
                    email: true
                },                                              
                userContactNumber: "required"                       
            },
            messages: {
                userName: "Please enter your Name",
                userContactNumber: "Please enter your Mobile number",                           
                email: "Please enter a valid email address",                                           
            },
            submitHandler: function(form) {
    
                // get values from textboxs 
                var uName = $('#userName').val();
                var mailId = $('#addressemailId').val();
                var mobNum = $('#userContactNumber').val();
    
                $.ajax({
                    url:"http://192.168.1.11/services/bookService4Homes.php",
                    type:"POST",
                    dataType:"json",
                    data:{type:"booking",Name:uName, Email:mailId, Mob_Num:mobNum },
                    //type: should be same in server code, otherwise code will not run
                    ContentType:"application/json",
                    success: function(response){
                        //alert(JSON.stringify(response));
                    },
                    error: function(err){
                        //alert(JSON.stringify(err));
                    }
                });
                return false; // block regular submit
            }
        });
    
    });
    

DEMO:http://jsfiddle.net/mh6cvf2u/