2014-01-19 49 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;