2015-10-13 71 views
7

我有一個內置到index.html中的html聯繫表單,然後我有一個mail.php文件發送郵件,也使用一些的JavaScript。當我填寫表格並提交時,我編碼它發送郵件,然後彈出一個成功消息框,然後重定向到index.html。提交後用成功消息替換HTML表單,表單使用單獨的php文件發送郵件

我想要的是將窗體替換爲成功消息,以避免頁面刷新,並避免彈出消息框。從index.html的

形式:

<form action="mail.php" method="POST"> 
    <div class="row uniform"> 
    <div class="6u 12u$(xsmall)"> 
     <input type="text" name="name" id="name" value="" placeholder="Name" /> 
    </div> 
    <div class="6u$ 12u$(xsmall)"> 
     <input type="email" name="email" id="email" value="" placeholder="Email" /> 
    </div> 
    <div class="12u$"> 
     <!--<div class="select-wrapper"> 

     </div>--> 
    </div> 
    <div class="12u$"> 
     <textarea name="message" id="message" placeholder="Enter your message" rows="6"></textarea> 
    </div> 
     <center><div class="g-recaptcha" data-sitekey=""></div></center> 
    <div class="12u$"> 
     <ul class="actions"> 
     <li><input type="submit" value="Send Message" class="special" /></li> 
     <li><input type="reset" value="Reset" /></li> 
     </ul> 
    </div> 
    </div> 
</form> 

php文件,電子郵件地址和驗證碼令牌原因很明顯去除:

<?php $name = $_POST['name']; 
$email = $_POST['email']; 
$message = $_POST['message']; 
$formcontent = "From: $name \n email: $email \n Message: $message"; 
$recipient = 'email address here'; 
$subject = 'Message from Website'; 
$mailheader = "From: $email \r\n"; 
$captcha; 
{ 
    if(isset($_POST['g-recaptcha-response'])) 
    { 
     $captcha=$_POST['g-recaptcha-response']; 
    } 
    if(!$captcha) 
    { 
     echo '<script language="javascript">'; 
     echo 'alert("Please check the Captcha")'; 
     echo '</script>'; 
     exit; 
    } 
    $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']); 
    if($response.success==false) 
    { 
    echo '<h2>Please do not try and spam here.</h2>'; 
    }else 
    { 
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!"); 
echo '<script language="javascript">'; 
echo 'alert("Your Message successfully sent, we will get back to you ASAP.");'; 
echo 'window.location.href="index.html";'; 
echo '</script>'; 
    } 
} ?> 

這是我居然看一個話題:

Clear form after submit and success message

回答

2

最好的辦法是使用AJAX。在你的html中包含jquery。

把你的形式包裝DIV中

<div class="something"> 
<!-- your form here --> 
</div> 

提交表單通過Ajax,而不是使用基本形式提交

//"idform" is the id of the form 
$("#idForm").submit(function() { 

    var url = "path/to/your/script.php"; // the script where you handle the form input. 

    $.ajax({ 
      type: "POST", 
      url: url, 
      // serialize your form's elements. 
      data: $("#idForm").serialize(), 
      success: function(data) 
      { 
       // "something" is the class of your form wrapper 
       $('.something').html(data); 
      } 
     }); 
    // avoid to execute the actual submit of the form. 
    return false; 
}); 

而最後一件事,你需要改變的是在你的PHP代碼

保持成功只有一個迴音

echo "Your Message successfully sent, we will get back to you ASAP."; 
+0

只是FYI:'data.message'將是未定義的,'數據'本身將是一個字符串 - '「您的消息已成功發送,我們會盡快回復您。」' – Pogrindis

+0

哎呀..我以爲我回來了格式化json ...謝謝,我會更新我的答案。 –

+0

@SumitPandey我有興趣嘗試你的答案,我實現了hunijkah提交的答案,但錯誤檢查出現錯誤,我一直在看它是什麼問題,但我是新來的Ajax和jQuery的。我的PHP文件已經有所有的錯誤檢查,所以我認爲PHP文件仍然會處理。你的答案能解決我的問題嗎?我非常接近完成這項工作,但錯誤檢查實際上是路上唯一的凹凸,如果表格填寫正確,它完美地工作。 – Troy

1

您可以使用jQ uery和Ajax表單提交。

首先,包括在你的腦袋元素的jQuery

<head> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 
</head> 

接下來,給你的表格一個id

<form id='mail_form' action="mail.php" method="POST"> 

某處添加一個跨度的ID = '錯誤'

<span id='error' style='color:red; font-weight:bold;'></span> 

將mail.php調整爲以下內容:

<?php 
$success = true; 
$errors = array(); 

$name = $_POST['name']; 
$email = $_POST['email']; 
$message = $_POST['message']; 
$formcontent = "From: $name \n email: $email \n Message: $message"; 
$recipient = 'email address here'; 
$subject = 'Message from Website'; 
$mailheader = "From: $email \r\n"; 
$captcha = false; 

    if(isset($_POST['g-recaptcha-response'])) 
    { 
     $captcha=$_POST['g-recaptcha-response']; 
    } 
    if(!$captcha) 
    { 
     $success = false; 
     array_push($errors, "Please check the captcha"); 
    } 
    $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']); 
    if($response.success==false) 
    { 
    $success = false; 
    array_push($errors, "Please do not try and spam here."); 

    } 

if ($success) 
{ 
    mail($recipient, $subject, $formcontent, $mailheader) or die("Error!"); 
} 

$output_array = array("success" => $success, "errors" => $errors); 
echo json_encode($output_array); 
?> 

然後,在你的頁面的底部添加做你所有的東西

<script> 
$('#mail_form').on('submit', function(){ 
    var dataIn = $(this).serialize(); //serialize turns the form data into a string that can be passed to mail.php. Try doing alert(dataIn); to see what it holds. 
    $.post("./mail.php", dataIn) 
     .done(function(dataOut) 
     { 
     //dataOut holds the response from mail.php. The response would be any html mail.php outputs. I typically echo out json encoded arrays as responses that you can parse here in the jQuery. 
     var myArray = JSON.parse(dataOut); 
     if (myArray['success'] == true) //Check if it was successfull. 
      { 
      $("#mail_form").html("Congrats! We just e-mailed you!"); 
      } 
     else //there were errors 
      { 
      $('#error').html(""); //Clear error span 

      $.each(myArray['errors'], function(i){ 
      $('#error').append(myArray['errors'][i] + "<br>"); 
      } 
     }); 
return false; //Make sure you do this or it will submit the form and redirect 
}); 
</script> 
+0

所以我用你的解決方案,它確實有效。然而,我的錯誤檢查不再有效,即我填寫了名字和消息,沒有填寫電子郵件或滴答滴答,它仍然帶有成功信息,我應該怎麼做以確保我仍然能夠得到相同的結果錯誤檢查,我得到像我用我的PHP文件? – Troy

+0

@Troy對「成功」所做的更改,並添加一個「.fail」,您可以根據服務器響應相應地輸出。 http://api.jquery.com/jquery.ajax/ – Pogrindis

+1

@Troy我只是更新了我的答案,包括錯誤檢查方式,我解釋了與JSON數組的評論 – hunijkah

1

首先您應該使用AJAX調用來提交表單。如果你堅持使用純JS腳本是這樣的(寫在5秒內 - 可能需要一些調整):

<script> 

document.forms['yourForm'].onsubmit = function(form) { // you have to add 'name' attribute to the form and replace 'yourForm' with it 
    var data = ... //here you have to get all the values from form elements and store them in data object. to make less changes to the script use the elements' names as object names 
    if (window.XMLHttpRequest) 
    { 
     var xhReq = new XMLHttpRequest(); 
    } 
    else 
    { 
     var xhReq = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 


    var method= 'POST') 
    var async = false; //you can actually set true here, it doesn't matter much in this case 
    var url = 'mail.php'; 
    xhReq.open(method, url, async); 
    xhReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
    xhReq.setRequestHeader("X-Requested-With", "XMLHttpRequest"); 
    xhReq.send(data); 



    document.getElementById("form's parent's ID goes here").innerHTML = "new content" 


    return false; 
} 
</script> 

比你要刪除php文件的所有回聲,因爲它不會顯示反正。您還可以爲該腳本添加一些更復雜的功能,例如檢查郵件功能是否正常工作(通過返回php文件中的內容並檢查JS中的AJAX響應)還是捕獲驗證碼錯誤。如果你願意走上這條路,那麼在jQuery中實現起來也會非常容易。

+0

加1爲本地xhr需求。 – Pogrindis

相關問題