PHPMailer使用ajax返回错误但仍然发送电子邮件

时间:2014-05-08 18:45:56

标签: php jquery ajax twitter-bootstrap email

遇到PHPMailer的一个问题,我似乎无法解决这个问题。

我有一个使用AJAX和PHP设置的简单表单。输入值被发送到php检查验证。批准后,PHP抓取所有相关数据(姓名,电子邮件,消息等)创建一条消息,发送回网站admin(info@email.com)。

这一切都有效,但每次从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 = 'XXXX@XXXX.com';                  // 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('XXXX@XXXX.com', '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);
?>

1 个答案:

答案 0 :(得分: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控制台中检查确切的输出。