2014-01-19 45 views
0

我在PHP中有一个web表单(form.php)上回应其具有以下布局:PHP表单提交,显示表单页面

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

mailer.php有检查数据的功能,验证它,并发送电子邮件给我。这一切都成功完成后,我想用alert/info消息重定向到我的表单页面。

mailer.php

梅勒功能看起来像:

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

我想在print_r消息上form.php在以下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警报等没有为我工作。

+0

@Chris感谢您的编辑,我们总是突出显示文件名? – CodeMonkey

+0

使用会话并将消息存储在变量中,例如: $ _SESSION ['message']。 或者使用Cokkies,然后将您的消息存储在变量中,例如: $ _COOKIE ['message']。 – phpCore

+1

@CodeMonkey,许多用户对文件名使用反引号(我发现它更容易阅读)。有些人**代替他们(或者同样)大胆他们**。我不会因为编辑而烦恼,但是'print_r'和'div'值得反引用,所以我也做了其他更改。 – Chris

回答

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> 
+0

$ _SESSION即将出现为NULL – CodeMonkey

+0

原始答案假定您的脚本中已经有其他会话开始,但我已使用适当的'session_start()'修改了答案。 –

+0

这是有效的。谢谢。我还可以通过邮件程序脚本改变课程吗? – CodeMonkey

0

而不是用php重定向用javascript做它。替换头('位置'),

echo <<<SCRIPT 

<script> 
setTimeout(function(){ 

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

</script> 

SCRIPT;