2013-07-11 45 views
0

我的網站上的表單是一個簡單的聯繫表單。 我會等形式顯示在發送的形式在同一頁上「成功&失敗」消息/失敗,沒有重新加載頁面。我明白我應該使用Ajax來做到這一點,但我無法使它工作。它一直說失敗,但形式發送,並在我的收件箱。Ajax表單成功和失敗消息不起作用

這是我正在使用的代碼。

HTML(單頁設計):

<form accept-charset="UTF-8" action="" class="form" id="contactus" method="post" name="contactus"> 
    <label for="nametag">Namn*</label> <input id="name" name="name" type="text" value=""> 
    <label for="emailtag">Email*</label> <input id="email" name="email" type="text" value=""> 
    <label for="phonetag">Telefon</label> <input id="phone" name="phone" type="text" value=""> 
    <label for="messagetag">Meddelande*</label><br> 
    <textarea id="message" name="message" style="width: 87%; height: 200px;"></textarea> 
<label class="placeholder">&nbsp;</label> <button class="submit" name="submit">Skicka</button> 
</form> 

<script> 

     $(function() { 
       $('#contactus').submit(function (event) { 
        event.preventDefault(); 
        event.returnValue = false; 
        $.ajax({ 
         type: 'POST', 
         url: 'php/mail.php', 
         data: $('#contactus').serialize(), 
         success: function(res) {alert(res); 
          if (res == 'successful') { 
           $('#status').html('Sent').slideDown(); 
          } 
          else { 
           $('#status').html('Failed').slideDown(); 
          } 
         }, 
         error: function() { 
          $('#status').html('Failed').slideDown(); 
         } 
        }); 
       }); 
      }); 
</script> 

PHP的:

<?php 
    $name = $_POST['name']; 
    $email = $_POST['email']; 
    $phone = $_POST['phone']; 
    $message = $_POST['message']; 
    $recipient = "[email protected]"; 
    $subject = "Webbkontakt"; 
    $formcontent = "Från: $name <br/> Email: $email <br/> Telefon: $phone <br/> Meddelande: $message"; 

    $headers = "From: " ."<[email protected]>" . "\r\n"; 
    $headers .= "Reply-To: ". "[email protected]" . "\r\n"; 
    $headers .= "MIME-Version: 1.0\r\n"; 
    $headers .= "Content-Type: text/html; charset=utf-8\r\n"; 

    if(mail($recipient, $subject, $formcontent, $headers)) 
    { 
     echo "successful"; 
    } 
    else 
    { 
     echo "error"; 
    } 
?> 
+0

什麼是從服務器的AJAX調用的響應? – David

+0

對不起,作爲noob,但我該如何檢查?我對此很陌生。 – user2566091

+1

'alert(res)'顯示什麼? –

回答

0

把@符號在郵件的前面。如果郵件已成功接受投遞,返回TRUE,否則返回FALSE。重要的是要注意,僅僅因爲郵件被接受發送,並不意味着郵件實際上會到達預定的目的地。換句話說,如果電子郵件已發送,則無法使用PHP進行檢測。

if(@mail($recipient, $subject, $formcontent, $headers)) 
{ 
    echo "successful"; 
}else{ 
    echo "error"; 
} 

然後改變成功和錯誤在AJAX如下:

success: function(res) { 
    if (res != "successful") { 
     $('#status').html('Failed').slideDown(); 
    } else { 
     $('#status').html('Sent').slideDown(); 
    } 
}, 

error: function(XMLHttpRequest, textStatus, errorThrown) { 
    alert("Error From AJAX"); 
}, 
+0

我現在這樣做了。你能看看最上面的鏈接嗎? – user2566091

+0

你知道你的消息文本框在窗體右邊的另一個div裏嗎?另外,你仍然錯誤? – Matto

+0

我移動了文本框,並且我仍然在頁面上顯示文本「失敗」,但彈出窗口顯示成功。窗體出現在我的收件箱中。 – user2566091