2016-03-24 41 views
2

現在我的網站打開了,用戶可以選擇他們想要訂購的東西。當他們想要提交訂單時,我只想發送一封電子郵件,但電子郵件未通過,我的頁面剛剛重新啓動。單擊按鈕時AJAX不會被調用?

的JavaScript/AJAX:

<script type="text/javascript"> 
    $(document).ready(
     function() { 
      $('#wholesaleOrderForm').submit(
       function() { 
        if (validateForm()) { 
         $.post("wholesale_form.php", 
          $('#wholesaleOrderForm').serialize(), 
          function(response) { 
           alert('response = ' + response); 
           if (response == "success") { 
            $('#ajax-msg').html("Thanks for subscribing!"); 
            $('#ajax-msg').style.color = "green"; 
            $('#ajax-msg').hide(5000); 
           } else { 
            $('#ajax-msg').html("Sorry, there is some error. Please try again."); 
            $('#ajax-msg').style.color = "red"; 
            $('#ajax-msg').hide(5000); 
           } 
          } 
         ); 
         // prevent postback 
         return false; 
        } else { 
         return false; 
        } 
       } 
      ); 
     } 
    ); 
</script> 

PHP代碼:

<?php 

$to = "[email protected]"; 
    $subject = 'hello'; 
    $message = "Hello!!"; 
    $headers = 'From: [email protected]_EMAIL.com'; 

    mail($to, $subject, $message, $headers); 

?> 
+0

定義'這不是working' –

+0

更新問題 –

+0

檢查'郵件的返回值',如果它是'true',那麼郵件服務器已經接受了郵件,所以這個問題不在PHP部分。 –

回答

2

你需要禁用與event.preventDefault形式的默認操作();

2

繼Julaine的建議,更改這兩個行:

$('#wholesaleOrderForm').submit(
    function() { 

這樣:

$('#wholesaleOrderForm').submit(
    function(e) { 
     e.preventDefault(); 
     //rest of your code 

說明:

形式通過導航到另一個頁面(通常在action="newpage.php"規定提交你的AJAX代碼在頁面離開之前沒有時間完成*請注意,如果一個action=屬性沒有指定,頁面只刷新 - AJAX的問題。


進一步建議,如果不工作:

(1)分而治之。大大減少你的代碼,直到它工作,然後逐漸將其餘部分添加回來,修復發現錯誤時的錯誤。

(2)減少了ajax到最小:

$('#wholesaleOrderForm').submit(function(e) { 
    e.preventDefault(); 
    $.post("wholesale_form.php", function(response) { 
     alert(response); 
    }); 
}); 

wholesale_form.php

<?php 
    echo 'Ajax is working';