2016-10-19 34 views
0

我想弄清楚一個簡單的方法來顯示一條消息被髮送或不在聯繫表單中。目前成功或失敗時,它將重定向到指定的成功或失敗頁面。我所要做的只不是重定向,也許顯示一個div,或模態或彈出式菜單,但我不確定如何在PHP中執行此操作。如何顯示聯繫表格提交成功/失敗的消息

形式:

<div class="col-lg-7 col-sm-7 contactboxform"> 
    <form action="contact_me.php" method="POST" id="contactform"> 
     <input type="text" name="name" placeholder="Name..." class="input-text"> 
     <input type="text" name="phone" placeholder="Phone Number..." class="input-text"> 
     <input type="email" name="email" placeholder="E-mail Address..." class="input-text"> 
     <input type="checkbox" name="interested"> 
     <textarea name="message" placeholder="What would you like to say?" class="input-text text-area" rows="7"></textarea> 
     <button type="submit" id="subbtn" class="btn btn-default btn-lg">Submit</button> 
    </form> 
    </div> 

PHP:

// send email 
if (!empty($name) && !empty($email) && !empty($phone) && !empty($message)) { 
    $success = mail($emailTo, $subject, $body, "From: <$emailFrom>"); 
} 
if ($success){ 
    header('Location: success.html'); 
} 
else { 
    header('Location: failed.html'); 
} 
//redirect to success page 

所以我只是不知道如何正確地在PHP上的成功,顯示特定DIV /彈出說。

在此先感謝

+1

您將需要AJAX,因爲PHP無法執行客戶端操作。 –

+0

重定向真的是個問題嗎?您可以重定向回到同一頁面,並在視圖中讀取「$ status」變量以顯示消息。它需要存儲在一個'$ _SESSION'中,以便在重定向時訪問它,並且最終不得不取消它。 – nerdlyist

+0

你能通過PHP觸發一個AJAX事件嗎? –

回答

1

你可以嘗試創建一個div,然後插入到它從一個AJAX請求的響應。

例如,添加到您的HTML代碼:

<div id="form_status"></div> 

當按鈕被點擊提交,執行AJAX請求:

<button type="submit" id="subbtn" class="btn btn-default btn-lg" onClick="validateForm();">Submit</button> 

而且validateForm功能可以是:

function validateForm() 
{ 
    var status = $('div#form_status'); 
    var form = $('form#contactform'); 
    $.ajax({ 
     url: 'your-php-file.php?'+form.serialize() 
    }).done(function(data){ 
     status.html(data); 
    }); 
} 

your-php-file.php上,您可以從表單wi中訪問所有數據th $_GET['input_name'],其中input_name是表單上輸入的name

使用此功能,您在your-php-file.php上打印的任何內容都將打印到div#form_status中,而無需刷新頁面。