使用AJAX返回表单验证

时间:2014-01-07 20:22:55

标签: javascript html ajax

我有一个联系表单,当点击提交时,我想要验证。

如果所有字段都返回有效,那么我希望AJAX返回处理消息,然后,当成功时,会显示带有插补名称的消息。

我的表单内容为:

<form onsubmit="return validateForm">
<input id="fname" class="textbox" name="fname" placeholder="First Nname" type="text" required="required" /><p>
<input id="sname" class="textbox" name="sname" placeholder="Surname" type="text" required="required" /><p>
<input id="email" class="textbox" name="email" placeholder="Email Address" type="email" required="required" /><p>
<input id="number" class="textbox" name="number" placeholder="Contact Number" type="email" /><p>
<textarea rows="10" id="message" class="textarea" name="message" placeholder="Message" required="required" ></textarea><p>
<input fname="myBtn" class="button" type="submit" value="Submit" onClick="javascript:ajax_post();">

我的表单验证内容为:

function validateForm()
{
var fname=document.forms["Form"]["fname"].value;
var sname=document.forms["Form"]["sname"].value;
var x=document.forms["Form"]["email"].value;
var telnum=document.forms["Form"]["telnum"].value;
var message=document.forms["Form"]["message"].value;

if(fname==null||fname=="")
    {
    alert("please enter your first name");
    return false;
    }

if(sname==null||sname=="")
    {
    alert("please enter your surname");
    return false;
    }

var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if(atpos<1||dotpos<atpos+2||dotpos+2>x.lenght)
    {
    alert("Not a valid email address.");
    return false;
    }

if(message==null||message=="")
    {
    alert("please enter a message");
    return false;
    }
}

AJAX脚本是:

function ajax_post(){
var hr = new XMLHttpRequest();
var url = "/additional/formfeedback.php";
var fname = document.getElementById("fname").value;
var vars = "fname="+fname;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("status").innerHTML = "Processing...";
}

返回的 PHP 是:

<?php 
echo 'Thank you '. $_POST['fname'] . ', we have recieved your message and will be back in touch shortly';
?>

单击提交按钮后,将返回PHP内容,然后验证开始 - 显然为时已晚。

如何正确验证,然后执行AJAX脚本?我不想使用任何其他库,例如jQuery。提前谢谢。

4 个答案:

答案 0 :(得分:3)

您应该将验证设置为提交按钮,然后在验证脚本的底部调用ajax脚本。

答案 1 :(得分:3)

ajax_post方法结束时致电validateForm

答案 2 :(得分:1)

有一点......在onclick中你不需要“javascript:”。它已经在期待javascript。

此外,如果您想使用Ajax提交数据,请将按钮更改为type =“button”(不提交)

答案 3 :(得分:-2)

<script type="text/javascript">

        $(document).ready(function(){
            $("#submit").click(function(){

                var fname  = $("#fname").val();
                var lname  = $("#lname").val();
                var email   = $("#email").val();
                var password = $("#Password").val();
                var cpassword = $("#cpassword").val();
                var gender = $("input[name=gender]:checked").val();
                var dob    = $("#dob").val();
                var image  = $("#image").val();
                var status  = $("#status").val();
                var submit  = $("#submit").val();

             var dataString='fname='+fname+'&lname='+lname+'&email='+email+ '&password='+password+ 
                '&cpassword='+cpassword+ '&gender='+gender+ '&dob='+dob+ '&image='+image+ '&status='+status+
                '&submit'+submit;

                if(fname=="" || lname=="" || email==""){
                    alert("please fill the fields");
                 }else if(fname.length < 5 || fname.length > 20){
                    alert("user name must be between 5 to 20 characters");
                 }else if(password.length < 5 || password.length > 8){
                    alert("password must be between 5 to 8 characters"); 
                 }else if(!gender){
                    alert("please select your gender");
                 }else if(!dob){
                    alert("please select  your birth day");
                 }else{
                    $.ajax({
                        type:"POST",
                        url:"create-user.php",
                        data:dataString,
                        cache:false,
                        success:function(result){
                            alert(result);
                        }
                    });//ajax closed
                 }

                 return false;
            });
        });
    </script>
                <div id="content" class="col-lg-10 col-sm-10">
                        <!-- content starts -->
                <div>
                <ul class="breadcrumb">
                    <li>
                        <a href="#">Home</a>
                    </li>
                        <li>
                            <a href="#">Forms</a>
                        </li>
                    </ul>
                </div>
        <div class="box-content">
                <div id="userRegis">
                    <div class="form-group">
                            <label for="exampleInputEmail1">First Name</label>
                            <input class="form-control" id="fname" placeholder="Enter First Name" type="text" name="fname">
                        </div>
                            <div class="form-group">
                                <label for="exampleInputEmail1">Last Name</label>
                                <input class="form-control" id="lname" placeholder="Enter Last Name" type="text">
                            </div>
                            <div class="form-group">
                                <label for="exampleInputEmail1">Email</label>
                                <input class="form-control" id="email" placeholder="Enter Email" type="text">
                            </div>

                            <div class="form-group">
                                <label for="exampleInputEmail1">Password</label>
                                <input class="form-control" id="Password" placeholder="Enter Password" type="password">
                            </div>

            <div class="form-group">
                    <label for="exampleInputEmail1">confirm Password</label>
                    <input class="form-control" id="cPassword" placeholder="Enter confirm Password" type="password" name="cpassword">
                </div>  

            <div class="form-group">        
                    <label for="exampleInputEmail1">Gender</label>
             <div class="radio">
                    <label>
                         <input type="radio" name="gender" id="gender" value="MALE">Male
                    </label>
                         <label>
                            <input type="radio" name="gender" id="gender" value="FEMALE">Female
                        </label>
                    </div>
                </div>
                <div class="form-group">
                    <label for="exampleInputEmail1">date of birth</label>
                    <input class="form-control" id="dob" placeholder="Enter Password" type="date" name="dob">
                </div>   

                <div class="form-group">
                        <label for="exampleInputEmail1">image</label>
                        <input class="form-control" id="image" placeholder="Enter Password" type="file" name="image">
                    </div>              

                    <div class="form-group">
                        <div class="control-group">
                    <label class="control-label" for="selectError">Status</label>
                    <div class="controls">
                        <select id="status" data-rel="chosen"  name="status">
                            <option value="0">SELECT</option>
                            <option value="1">ACTIVE</option>
                            <option value="2">PENDING</option>

                        </select>
                    </div>
                </div>
             <br>
            <input type="submit" name="submit" id="submit" value="create user" class="btn btn-default">
        </div>
    </div>
</div>  
</div>