错误400错误请求Ajax发送SMTP电子邮件

时间:2016-10-18 14:43:08

标签: php jquery ajax phpmailer

我几个星期以来一直坚持这个问题。我正在尝试使用在同一页面上提供的表单数据发送SMTP电子邮件。

我已经在网上跟踪了很多例子,但弗兰肯斯坦似乎并不能让它对我起作用。我认为问题在于从表单中获取数据。

HTML

<div id="form-messages"></div>
          <form method="post" action="" id="main-contact-form" >
            <div class="row wow fadeInUp" data-wow-duration="1000ms" data-wow-delay="300ms">
              <div class="col-sm-6">
                <div class="form-group">
                  <input type="text" id="name" name="name" class="form-control" placeholder="Name" required="required">
                </div>
              </div>
              <div class="col-sm-6">
                <div class="form-group">
                  <input type="email" id="email" name="email" class="form-control" placeholder="Email Address" required="required">
                </div>
              </div>
            </div>
            <div class="form-group">
              <input type="text" id="subject" name="subject" class="form-control" placeholder="Subject" required="required">
            </div>
            <div class="form-group">
              <textarea name="message" id="message" class="form-control" rows="4" placeholder="Enter your message" required="required"></textarea>
            </div>                        
            <div class="form-group">
              <input type="submit" class="btn-submit">
            </div>
          </form> 

的JQuery / AJAX

var form = $('#main-contact-form');
form.submit(function(event){
    event.preventDefault();
    var form_status = $('<div class="form_status"></div>');
    $.ajax({
        url: "http://localhost:8080/adb2/mailer.php",
        type: "POST",
        beforeSend: function(){
            form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn() );
        }
    }).done(function(data){
        form_status.html('<p class="text-success">Thank you for contacting us. We will contact you as soon as possible!</p>').delay(3000).fadeOut();
    });
});

PHP(mailer.php)

    <?php
    // Only process POST reqeusts.
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // Get the form fields and remove whitespace.
        $name = strip_tags(trim($_POST["name"]));
        $name = str_replace(array("\r","\n"),array(" "," "),$name);
        $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
        $subject = trim($_POST['subject']);
        $message = trim($_POST["message"]);

         // Check that data was sent to the mailer.
        if ( empty($name) OR empty($subject) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            // Set a 400 (bad request) response code and exit.
            http_response_code(400);
            echo "Oops! There was a problem with your submission. Please complete the form and try again.";
            exit;
        }

        require("phpmailer/PHPMailerAutoload.php");

        $mail = new PHPMailer();

        $mail->IsSMTP();
        $mail->Host = "xxxxxxxxxxxxxxxx"; 
        $mail->SMTPAuth = true;

        $mail->Username = "xxxxxxxxxxxxxxx";  // SMTP username
        $mail->Password = "xxxxxxxxxxxxxxx"; // SMTP password

        $mail->From = $email;

        $mail->AddAddress("xxxxxxxxxxx", "Website");

        $mail->WordWrap = 50;
        $mail->IsHTML(true);
        $mail->Subject = $subject;

        $mail->Body    = $message;
        $mail->AltBody = $message;

        // Send the email.
        if ($mail->Send()) {
            // Set a 200 (okay) response code.
            http_response_code(200);
            echo "Thank You! Your message has been sent.";
        } else {
            // Set a 500 (internal server error) response code.
            http_response_code(500);
            echo "Oops! Something went wrong and we couldn't send your message.";
        }

    } else {
        // Not a POST request, set a 403 (forbidden) response code.
        http_response_code(403);
        echo "There was a problem with your submission, please try again.";
    }
?>

提交表单后,返回“POST http://localhost:8080/adb2/mailer.php 400(错误请求)”

如果有人能指出我正确的方向,我会非常感激!谢谢你的阅读!

1 个答案:

答案 0 :(得分:0)

经过多次挖掘后计算出来。我添加了一个名为“formData”的变量并序列化了表单。之后我把它传递给了ajax调用,它现在正在运行。下面是修复的JQuery / Ajax。

var form = $('#main-contact-form');
var formMessages = $('#form-messages');
form.submit(function(event){
    event.preventDefault();
    var formData = $(form).serialize();
    var form_status = $('<div class="form_status"></div>');
    $.ajax({
        url: "http://localhost:8080/adb2/mailer.php",
        type: "POST",
        data: formData,
        beforeSend: function(){
            form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn() );

        }
    }).done(function(response){
        form_status.html('<p class="text-success">Thank you for contacting us. We will contact you as soon as possible!</p>').delay(3000).fadeOut();
        // Make sure that the formMessages div has the 'success' class.
        $(formMessages).removeClass('error');
        $(formMessages).addClass('success');

        // Set the message text.
        $(formMessages).text(response);

        // Clear the form.
        $('#name').val('');
        $('#email').val('');
        $('#subject').val('');
        $('#message').val('');
    }).fail(function(response) {
        // Make sure that the formMessages div has the 'error' class.
        $(formMessages).removeClass('success');
        $(formMessages).addClass('error');
    });
});