2015-05-31 160 views
2

我在嘗試通過ajax提交表單時遇到了一些奇怪的問題。對於$(form).on('submit'),這個工作原理,即使使用preventDefault(),它也會重定向到email.php腳本,但是我傳遞了值併發送了電子郵件。Ajax請求表單提交問題

$('#submit')。on('click')在請求有效載荷中顯示它正在發送,但是電子郵件被觸發,導致沒有內容,但是頁面沒有重新加載。

$(function(){ 
    var form = document.getElementById('ajax-contact'); 

    // $(form).on('sumbit', function(e){ // This works but redirects to the email processing page. 
    $('#submit').on('click', function(e){ 
     var data = { 
      name: $("input[name='name']").val(), 
      email: $("input[name='email']").val(), 
      message: $("input[name='message']").val() 
     }; 

     $.ajax({ 
      type: "POST", 
      url: "/api/email.php", 
      contentType: "application/json", 
      data: JSON.stringify({ "email": $("#email").val(), "name": $("#name").val(), "message": $("#message").val() }), 
      beforeSend: function(){ 
       $("#submit").attr("value","Processing your request..."); 
      }, 
      success: function(data){ 
       $("#submit").attr("value","Thank you, I will get back to you as soon as possible."); 
      }, 
      error: function(xhr, textStatus){ 
       if(xhr.status === 404) { 
        $('#submit').attr("value","There was an ERROR processing your request"); 
       } 
      } 
     }); 

     e.preventDefault(); 
    }); 
}); 

這裏是PHP腳本。

<?php 

if($_SERVER['REQUEST_METHOD'] === 'POST') { 
    echo 'Email Processed'; 
    $recipient = '[email protected]'; 

    $name = $_POST['name']; 
    $email = $_POST['email']; 
    $msg = $_POST['message']; 

    $msg_body = "Name: " . $name . "Email: " . $email . 'Message: ' . $msg; 

    mail($recipient,'Message from: ' . $name , $msg_body); 
} else { 
    return; 
} 

?> 
+0

如果你的表單代碼'action'屬性是有刪除。並且'e.preventDefault()'不存在? –

+0

通常'e.preventDefault()'放在頂部,但這可能不是問題的原因。你可以創建一個重現問題的小提琴嗎? – PeterKA

+0

請注意,您的常規提交可能是由您的事件處理程序中的錯字造成的,'sumbit'應該是'submit'。 – jeroen

回答

1

您還沒有發送鍵 - 值對到服務器,但一個單一的字符串:

data: JSON.stringify({ "email": $("#email").val(), "name": $("#name").val(), "message": $("#message").val() }), 

應該是:

data: { "email": $("#email").val(), "name": $("#name").val(), "message": $("#message").val() }, 

或:

// you already generated an object with the data 
data: data, 

你實際上可以發送一個字符串,但比你會需要讀取原始輸入。

你真的應該抓住的形式,以防有人提出不按下按鈕,但使用回車鍵來代替:

$(form).on('submit', function(e){ 
      ^^^^^^ small typo here 
    e.preventDefault();