表单提交 - 提交后不刷新/隐藏Div

时间:2016-08-09 12:09:02

标签: php jquery html

当我提交表单时,它会使用此代码将我重定向回同一页面

PHP

if( empty($errors))
{
$to = $myemail; 
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n Email: $email_address \n Message \n $message"; 

$headers = "From: $myemail\n"; 
$headers .= "Reply-To: $email_address";

mail($to,$email_subject,$email_body,$headers);

//redirect to the 'thank you' page
header('Location: index.html');
}

我想要它做的是保持在同一页面而不刷新然后隐藏div ..

HTML

            <div class="footer">
            <div id="containerfooter">
                <form method="POST" name="contactform" action="contact-form-handler.php" class="NewsLetter" class="NL__field NL__email"> 
                <p>
                <label for='name'>Your Name:</label> <br>
                <input type="text" name="name" class="NL__field NL__email">
                </p>
                <p>
                <label for='email'>Email Address:</label> <br>
                <input type="text" name="email"> <br>
                </p>
                <p>
                <label for='message'>Message:</label> <br>
                <input type="text" name="message">
                </p>
                <input type="submit" value="Submit"><br>
                </form>
            </div>
        </div>

JQuery的

        $('form').submit(function(){
        $('#containerfooter').hide();  
    });

1 个答案:

答案 0 :(得分:1)

表格与AJAX

表单允许您获取用户输入的数据并将其发送到另一个PHP文件进行处理。但是,在提交表单时,导航将移动到另一个PHP页面(表单标记上的action=""属性中指定的页面:

<form method="POST" name="contactform" action="contact-form-handler.php" class="NewsLetter" class="NL__field NL__email">

在上面的代码中,点击提交按钮后,浏览器会导航到contact-form-handler.php

发明AJAX是为了解决这个问题,允许您将数据发送到第二个PHP文件,并(可选)接收不同的数据/ html ,而无需更改或刷新当前页面 < /强>

这是一篇SO帖子,其中包含一些非常简单的AJAX示例。这并不困难 - 只需将示例复制到您的服务器并使它们在您的服务器上运行。和他们一起玩吧。您花费的十五分钟将为您节省 小时。

AJAX request callback using jQuery

注意:在这个时代,几乎不需要使用FORMs。一切都可以通过AJAX完成 - 而且它很简单,为什么不呢?

注意2:将AJAX与<form></form>标记一起使用时,必须使用e.preventDefault()来阻止表单标记离开当前页面(表单标记的默认操作):

$('myButton').submit(function(evt){
    evt.preventDefault();
    //the rest of your js code, including ajax code block