2014-10-02 143 views
1

給定一個標準的html表單,如下面的表單;使用php發送郵件

<form method="post" action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>> 
          <div class="row half"> 
           <div class="6u"><input type="text" placeholder="Name" name="name" /></div> 
           <div class="6u"><input type="text" placeholder="Email" name="email" /></div> 
          </div> 
          <div class="row half"> 
           <div class="12u"><textarea name="message" placeholder="Message" name="message"></textarea></div> 
          </div> 
          <div class="row"> 
           <div class="12u"> 
            <ul class="actions"> 
             <li><input type="submit" class="button" value="Send Message" name="submit" /></li> 
             <li><input type="reset" class="button alt" value="Clear Form" name="clear"/></li> 
            </ul> 
           </div> 
          </div> 
         </form> 

而下面的PHP

if(isset($_POST['submit'])){ 
    $to = "[email protected]"; // this is your Email address 
    $from = $_POST['email']; // this is the sender's Email address 
    $name = $_POST['name']; 
    $subject = "Website Enquiry"; 
    $message = $name . " wrote the following:" . "\n\n" . $_POST['message']; 
    $headers = "From:" . $from; 
    $headers2 = "From:" . $to; 

    if(isValidString($from) && isValidString($name) && isValidString($message)){ 
     mail($to,$subject,$message,$headers); 
    } 
} 

它可以發送電子郵件,但是,這種方法會導致幾個問題。因爲我的表單位於頁面的底部,所以當點擊發送時,頁面被重定向回來,並且焦點返回到頁面的頂部。

什麼是正確的方式來提供足夠的用戶反饋,讓用戶知道電子郵件已發送,是否可以導航回頁面並自動滾動到底部 - 允許我將發送按鈕更改爲綠色或什麼?

如果失敗了,是否有更好的方法來做到這一點?

謝謝

+0

如果我瞭解你想添加一個反饋。你可以做一些事情(只是一個例子)'''if($ mail){header('Location:form.php?status = success'); }''''並在form.php中添加''''$ response = $ _GET ['status']; if($ response =='success'){echo「Mail has been sent」; }'''' – 2014-10-02 08:50:32

回答

0

表單動作應該指向頁面本身(就像它在你的例子中那樣),所以你可以從驗證中顯示錯誤消息(就像你不這樣做)。

如果表格是不是在你的頁面的頂部,你可以添加錨點:

<h2><a name="theForm">The form</a></h2> 
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>#theForm"> 

如果表單正確處理(=郵件發送),這是很好的做法,重定向到另一個頁面,展示成功消息。所以按F5不會再次提交表單(併發送另一封郵件)。

if (mail($to,$subject,$message,$headers)) { 
    // redirect to page showing success message and exit script 
} else { 
    // redirect to page showing error message and exit script 
} 

我通常重定向到同一頁面了,但附加一個參數($_SERVER["PHP_SELF"].'?mail_success=1'),然後我決定是否顯示成功消息,錯誤消息或表單模板內:

if (isset($_REQUEST['mail_success'])) { 
    // show success message 
} elseif (isset($_REQUEST['mail_error'])) { 
    // show error message, technical issues, try again bla bla 
} else { 
    // show the form (including validation errors if necessary) 
} 
4

在窗體前添加一個錨鏈接。 <a id="anchorName"></a>

將表單發佈到錨點。

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>#anchorName">

0

你可以使用一個XMLHttpRequest提交表單,並取消按提交的默認操作。 jQuery的.post()和event.preventDefault()方法尤其擅長。