2014-05-08 112 views
1

運行到PHPMailer的問題,我似乎無法包裝我的頭。PHPMailer返回ajax錯誤,但仍然發送電子郵件

我有一個簡單的表單設置與AJAX和PHP。輸入值被髮送到php檢查驗證。獲得批准後,PHP會抓取所有相關數據(名稱,電子郵件,消息等),並創建一條消息發送回站點admin([email protected])。

這一切都有效,但每次都從ajax請求返回錯誤函數。特別是在表單本身提交,驗證併發送電子郵件之後,這讓我瘋狂。不知道最新發生的事情,但我的代碼是相當裸露的,沒有什麼幻想發生,但我得到一個奇怪的錯誤。

<form id="form-contact" method="POST" action="form-contact.php" role="form"> 
     <div class="row"> 
      <div class="col-md-6"> 
       <div class="form-group name-group"> 
        <label for="name">Full Name</label> 
        <input type="text" name="name" id="name" class="form-control" placeholder="Full Name" tabindex="1" > 
       </div> 
      </div> 
      <div class="col-md-6"> 
       <div class="form-group email-group"> 
        <label for="email">Email</label> 
        <input type="email" name="email" id="email" class="form-control" placeholder="Email Address" tabindex="2" > 
       </div> 
      </div> 
     </div> 
     <div class="form-group subject-group"> 
      <label for="subject">Subject</label> 
      <input type="text" name="subject" id="subject" class="form-control" placeholder="Subject" tabindex="3" > 
     </div> 
     <div class="form-group message-group"> 
      <label for="message">Message</label> 
      <textarea name="message" id="message" class="form-control" placeholder="Message" tabindex="4" ></textarea> 
     </div> 
     <div class="row center"> 
      <button class="btn btn-secondary" name="submit" tabindex="4">submit</button> 
     </div> 
    </form> 

的JavaScript

$('#form-contact').submit(function(e){ 
    e.preventDefault(); 
    $.ajax({ 
    type:$(this).attr('method'), 
    url: $(this).attr('action'), 
    data: $(this).serialize(), 
    dataType: 'json', 
    success: function(data){ 
     console.log(data); 
    }, 
    error: function(err){ 
     console.log('failed'); 
     console.log(err); 
    } 
    }) 
}); 

PHP

<?php 

    date_default_timezone_set('America/New_York'); 
    require '../includes/phpmailer/PHPMailerAutoload.php'; 

    $data = array(); 
    $errors = array(); 

    if (empty($_POST["name"])) { 
     $errors["name"] = "Name is required"; 
    } 

    if (empty($_POST["email"])){ 
     $errors["email"] = "Email is required"; 
    } 

    if (empty($_POST["message"])){ 
     $errors["message"] = "Message is required"; 
    } 

    if (! empty($errors)){ 
     $data["success"] = false; 
     $data["errors"] = $errors; 
    } else { 
     $data['success'] = true; 
     $data['name'] = $name; 
     $data['email'] = $email; 
     $data['subject'] = $subject; 
     $data['message'] = $message; 



    } 
    $name =  filter_var($_POST["name"], FILTER_SANITIZE_STRING); 
    $email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL); 
    $formMessage = filter_var($_POST["message"], FILTER_SANITIZE_STRING); 
    $message = '<p>The following request was sent from: </p>'; 
    $message .= '<p>Name: ' . $name . '</p>'; 
    $message .= '<p>Email: ' . $email . '</p>'; 
    $message .= '<p>Message: ' . $formMessage .'</p>'; 


    $mail = new PHPMailer; 

    $mail->isSMTP();                 // Enable SMTP authentication 
    $mail->SMTPAuth = true;        // Set mailer to use SMTP 
    $mail->Host = 'server.bluehost.com';    // Specify main and backup server (this is a fake name for the use of this example)    

    $mail->Username = '[email protected]';     // SMTP username 
    $mail->Password = 'XXXXXX';       // SMTP password 
    $mail->SMTPSecure = 'ssl';       // Enable encryption, 'ssl' also accepted         
    $mail->Port = 465;       

    $mail->From = $email; 
    $mail->FromName = $name; 
    $mail->AddReplyTo($email,$name); 
    $mail->addAddress('[email protected]', 'Person Name'); // Add a recipient 

    $mail->WordWrap = 50;        // Set word wrap to 50 characters 
    $mail->isHTML(true);        // Set email format to HTML 

    $mail->Subject = 'Here is the subject'; 
    $mail->Body = 'This is the HTML message body <b>in bold!</b>'; 
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; 

    if(!$mail->send()) { 
     echo 'Message could not be sent.'; 
     echo 'Mailer Error: ' . $mail->ErrorInfo; 
     exit; 
    } 

    echo 'Message has been sent'; 

    echo json_encode($data, JSON_PRETTY_PRINT); 
?> 
+0

很可能PHP除了輸出JSON(如警告或通知)之外還輸出其他一些內容,導致JavaScript無法解析JSON。如果有'dataType:'json',jQuery將運行錯誤ajax處理程序,如果它無法解析JSON。 – MrCode

+0

@MrCode是否有一種方法可以確定其生成的其他內容?你是否暗示'內容'不是有害的?第一次這樣做,所以不知道會發生什麼。 – patrick

+0

@patrick它就在你的'json_encode()'行之前......你應該把所有的消息添加到你的'$ data'數組中。 – jeroen

回答

2

jQuery是因爲您指定期待回JSON。所以你需要確保你輸出有效的json。你可以使用json_encode()來做到這一點,但是你必須確保只有它返回到瀏覽器而沒有其他東西。

所以,你應該改變:

if(!$mail->send()) { 
    echo 'Message could not be sent.';   // No other echoes except the very last one 
    echo 'Mailer Error: ' . $mail->ErrorInfo; // and here 
    exit; 
} 

echo 'Message has been sent';     // and here 

echo json_encode($data, JSON_PRETTY_PRINT); 

喜歡的東西:

if(!$mail->send()) { 
    $data['error']['title'] = 'Message could not be sent.'; 
    $data['error']['details'] = 'Mailer Error: ' . $mail->ErrorInfo; 
    exit; 
} 

$data['success']['title'] = 'Message has been sent'; 

echo json_encode($data); 

注意,其他 - 意想不到的 - 通過你的PHP腳本的輸出可能包括像PHP的警告,但你可以檢查的準確在javascript控制檯中輸出。

+1

終於得到它的工作。 IT是這個的混合體,並且正是我在其中迴應$數據的地方。 $ errors數據被傳回爲JSON,它實際上並沒有指定我的錯誤,只是一個大對象日誌。將echo json_encode($data)腳本移動到我的if/else之外允許它記錄任何通過的數據。 謝謝,Jeroen! – patrick

+0

正如jeroen所說,你不能迴應,如果它不是json。因此,如果您使用class.smtp.php或class.pop3.php,則必須在使用ajax之前評論一些回聲 – AlexGach

相關問題