PHP表单提交以在表单页面上显示响应

时间:2014-01-19 13:43:32

标签: php

我在PHP中有一个Web表单(form.php),它具有以下布局:

<form method="post" action="mailer.php" class="form-horizontal">

mailer.php具有检查数据,验证数据并向我发送电子邮件的功能。完成所有操作后,我想重定向到带有警报/信息消息的表单页面。

mailer.php中的邮件程序功能如下:

    $httpReferer = $_SERVER['HTTP_REFERER'];
    print_r("Form submitted successfully. We will contact you soon !");
    header('Location: '. $httpReferer) ;

我希望在以下print_r form.php的{​​{1}}上的div中收到消息,

<div class="alert alert-info">
    <button type="button" class="close" data-dismiss="alert">&times;</button>
    Make sure to fill all the fields with correct values before sending your email!
</div>

我能够重定向,但没有任何消息。尝试回声,尝试使用JavaScript警报等没有为我工作。

2 个答案:

答案 0 :(得分:1)

mailer.php脚本中,您可以打印邮件或使用header(),但不能同时执行这两项操作。如果您想重定向到form.php并在其中添加一条消息,则可以使用$_GET$_SESSION。使用$_GET看起来像这样:

$httpReferer = $_SERVER['HTTP_REFERER'];
$message = "Form submitted successfully. We will contact you soon !";
header('Location: '. $httpReferer . "?message=" . urlencode( $message ));

然后你的div会是这样的:

<div class="alert alert-info">
    <button type="button" class="close" data-dismiss="alert">&times;</button>
    <?php echo $_GET['message']; ?>
</div>

但我认为$_SESSION解决方案会更清晰,因为它不会使地址栏与您的消息混乱:

$httpReferer = $_SERVER['HTTP_REFERER'];
session_start();
$_SESSION['message'] = "Form submitted successfully. We will contact you soon !";
header('Location: '. $httpReferer);

<? session_start(); ?>
<div class="alert alert-info">
    <button type="button" class="close" data-dismiss="alert">&times;</button>
    <?php echo $_SESSION['message']; ?>
</div>

答案 1 :(得分:0)

而不是使用php重定向使用javascript进行重定向。用,

替换标题('位置')
echo <<<SCRIPT

<script>
setTimeout(function(){

document.location = '$_SERVER[HTTP_REFERER]';   
}, 2000);

</script>

SCRIPT;