2013-11-01 42 views
1

我正在做一個簡單的聯繫表單,我有一個老學校的PHP郵件程序mail.php和一個jQuery的頭版從我打電話給它。jQuery AJAX聯繫表格與PHP郵件跳轉到郵件頁面

,因爲我想它的工作,它應該已經住同一頁面上,但它實際上跳到mail.php並顯示消息 Thank you for contacting me. I'll try to reach you ASAP. 雖然它發送郵件,那還是因爲這是不是不能接受我的意圖。任何人都可以在這裏發現我做錯了什麼嗎?

任何幫助表示讚賞。

PHP:

<?php 
$name = trim($_POST['name']); 

$email = trim($_POST['email']); 

if(function_exists('stripslashes')) { 
    $message = stripslashes(trim($_POST['message'])); 
} else { 
    $message = trim($_POST['message']); 
} 

$emailTo = '[email protected]'; 
$subject = 'Contact Form Submission from '.$name; 
$sendCopy = trim($_POST['sendCopy']); 
$body = "Name: $name \n\nEmail: $email \n\nMessage: $message"; 
$headers = 'From: Saddi website <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email; 

mail($emailTo, $subject, $body, $headers); 
echo "Thank you for contacting me. I'll try to reach you ASAP."; 
return true; 
?> 

FORM(引導標記出現的很多,所以要保持乾淨,我只是發佈):

<form class="form" action="mail.php" method="post" id="contact-form"> 


        </form> 

而且在這裏不用我的AJAX:

var data_string = jQuery('#contact-form').serialize(); 

    jQuery.ajax({ 
     type: "POST", 
     url: "mail.php", 
     data: {name:name,email:email,message:message}, 
     timeout: 6000, 
     error: function(request,error) { 
      if (error == "timeout") { 
       jQuery('#timedout').fadeIn('slow'); 
       setTimeout(function() { 
        jQuery('#timedout').fadeOut('slow'); 
       }, 3000); 
      } 
      else { 
       jQuery('#state').fadeIn('slow'); 
       jQuery("#state").html('The following error occured: ' + error + ''); 
       setTimeout(function() { 
        jQuery('#state').fadeOut('slow'); 
       }, 3000); 
      } 
     }, 
     success: function() { 
      jQuery('span.valid').remove(); 
      jQuery('#thanks').fadeIn('slow'); 
      jQuery('input').val(''); 
      jQuery('textarea').val(''); 
      setTimeout(function() { 
       jQuery('#thanks').fadeOut('slow'); 
      }, 3000); 
     } 

回答

1

首先,我會推薦你​​使用jQuery表單插件,這對於這種ajax文章和驗證非常有幫助。

jQuery Form

其次,你可以使用event.preventDefault();爲了避免該鏈接的默認操作,但它會真的取決於你是如何觸發你的形式向Ajax代碼

event.preventDefault

+0

謝謝您的回答丹尼,顯然我的AJAX代碼沒有被調用。所以我正在重新開始工作,如果我的新工作不成功,我會試試這個。這是一件容易的事情。雖然我希望我沒有接近傳球。 – CalZone

+0

歡迎@calZone如果它適合你,請隨時接受答案,如果不告訴我,我會爲你設置一個jsfiddle。另外嘗試檢查瀏覽器控制檯是否有javascript錯誤,以查看是否可以在那裏獲得提示。 – DannyG