Ajax表单在容器div中提交和验证

时间:2013-11-22 21:39:00

标签: javascript php jquery ajax validation

[------嘿伙计们感谢您的帮助,但这个问题已经解决了------]

如果我尝试的几乎是不可能的,请告诉我们。

好的,我希望创建一个可列表的表单,标签必须动态地将链接路径加载到指定的容器div中。现在这很容易。

好吧所以我有我的可显示导航并且表单加载正常但是当我尝试验证这些表单时,它们会从容器区域跳出并跳到一个全新的页面。现在我想要的是将表单加载到指定的div并在该div中进行验证,当按下提交/发送按钮时,我希望该表单连接到php发送脚本并在成功提交后想要在同一个指定的div中显示成功消息。所以基本上我希望所有事情都像iframe一样被包含。

请求我帮助我。我尝试过并试过,但没有任何作用:这是我的代码:

html标记:

<section id="form-tab-block">

    <div id="form-menu-wrapper">

        <div id="form-tab-menu">
            <a class="menu_top" href="form/form_one.html">Form one</a>
    <a class="menu_top" href="form/form.html">Form two</a>
    <a class="menu_top" href="form/form.html">Form three</a>
    <a class="menu_top" href="contactform/index.php" Onclick="return                       false;">Form four</a>
        </div>

        <div id="content_area"></div>

    </div>

</section>

nav js script:

$('.menu_top').click(function() {

var href= $(this).attr('href');
$('#content_area').hide().load(href).slideDown('slow');

return false;
});



$(function() {
$('a').click(function(e) {

    // you usually want to prevent default for handling link clicks,

    // otherwise the browser follows the href (if that's intended skip this)

    //e.preventDefault();

    $('a').not(this).removeClass('Nav_Current');

    $(this).addClass('Nav_Current');

});

});

这是我的表格:

<?php
//If the form is submitted
if(isset($_POST['submit'])) {

//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
    $hasError = true;
} else {
    $name = trim($_POST['contactname']);
}

//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
    $hasError = true;
} else {
    $subject = trim($_POST['subject']);
}

//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '')  {
    $hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$",     trim($_POST['email']))) {
    $hasError = true;
} else {
    $email = trim($_POST['email']);
}

//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
    $hasError = true;
} else {
    if(function_exists('stripslashes')) {
        $comments = stripslashes(trim($_POST['message']));
    } else {
        $comments = trim($_POST['message']);
    }
}

//If there is no error, send the email
if(!isset($hasError)) {
    $emailTo = 'your@emailaddress.com'; //Put your own email address here
    $body = "Name: $name \n\nEmail: $email \n\nSubject: $subject     \n\nComments:\n $comments";
    $headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;

    mail($emailTo, $subject, $body, $headers);
    $emailSent = true;
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"                "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>Accessible PHP Contact Form with JQuery Validation</title>

<link rel="stylesheet" href="css/screen.css" type="text/css" media="screen" />

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"     type="text/javascript"></script>
<script     src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.pack.js"     type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
// validate signup form on keyup and submit
var validator = $("#contactform").validate({
    rules: {
        contactname: {
            required: true,
            minlength: 2
        },
        email: {
            required: true,
            email: true
        },
        subject: {
            required: true,
            minlength: 2
        },
        message: {
            required: true,
            minlength: 10
        }
    },
    messages: {
        contactname: {
            required: "Please enter your name",
            minlength: jQuery.format("Your name needs to be at least     {0} characters")
        },
        email: {
            required: "Please enter a valid email address",
            minlength: "Please enter a valid email address"
        },
        subject: {
            required: "You need to enter a subject!",
            minlength: jQuery.format("Enter at least {0} characters")
        },
        message: {
            required: "You need to enter a message!",
            minlength: jQuery.format("Enter at least {0} characters")
        }
    },
    // set this class to error-labels to indicate valid fields
    success: function(label) {
        label.addClass("checked");
    }
});
});
</script>
</head>

<body>
<div class="wrapper">
<div id="contactWrapper" role="form">

    <h1 role="heading">Send us a message</h1>

    <?php if(isset($hasError)) { //If errors are found ?>
        <p class="error">Please check if you've filled all the fields with     valid information and try again. Thank you.</p>
    <?php } ?>

    <?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
        <div class="success">
            <p><strong>Email Successfully Sent!</strong></p>
            <p>Thank you for using our contact form <strong><?php echo     $name;?></strong>! Your email was successfully sent and we 'll be in touch with you soon.    </p>
        </div>
    <?php } ?>

    <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"     id="contactform">
        <div class="stage clear">
            <label for="name"><strong>Name: <em>*</em></strong></label>
            <input type="text" name="contactname" id="contactname"     value="" class="required" role="input" aria-required="true" />
        </div>

        <div class="stage clear">
            <label for="email"><strong>Email: <em>*</em></strong></label>
            <input type="text" name="email" id="email" value="" class="required email" role="input" aria-required="true" />
        </div>

        <div class="stage clear">
            <label for="subject"><strong>Subject: <em>*</em></strong>    </label>
            <input type="text" name="subject" id="subject" value=""     class="required" role="input" aria-required="true" />
        </div>

        <div class="stage clear">
            <label for="message"><strong>Message: <em>*</em></strong>    </label>
            <textarea rows="8" name="message" id="message"     class="required" role="textbox" aria-required="true"></textarea>
        </div>

        <p class="requiredNote"><em>*</em> Denotes a required field.</p>

        <input type="submit" value="Send Message" name="submit"     id="submitButton" title="Click here to submit your message!" />
    </form>

</div>

</div>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

我认为有两个问题(如果我错了,请纠正我)。 1)验证不会触发,2)提交表格后,整个页面会刷新,是否正确?

对于1,您应该添加一个事件处理程序。我不确定你是否已正确实现了验证插件,如果它是this one我认为你有。如果您还没有,并且有一个javascript错误,表单将简单地发布到<?php echo $_SERVER['PHP_SELF']; ?>,这就是页面刷新的原因。在页面的头部尝试这个(暂时删除其他JavaScript):

<script>
    $(function() {
        $("#contactform").on("submit", function(event){
            event.preventDefault();
            alert("I was submitted");
        });
    });
</script>

提交后,您是否看到提醒框?您现在可以尝试重新插入validate()代码,如下所示:

<script>
    $(function() {
        $("#contactform").validate({ ... options ... });
    });
</script>

至于第2部分,如果您想将div#content_area用作iframe,则需要更多javascript。您最好的选择是通过AJAX发送表单(验证插件可能能够为您处理,read here)并将返回值重新插入div#content_area。看起来有点像这样:

$("#contactform").validate({
    ...,
    submitHandler: function(form) {
        $.ajax(form.prop("action"), {
            data: form.serialize(),
            type: "post",
            always: function(response) {
                $("#content_area").html(response);
            }
        });
    }
});