2016-10-18 1 views
0

Я застрял в этом вопросе в течение нескольких недель. Я пытаюсь отправить SMTP-адрес электронной почты, используя данные формы, предоставленные во время пребывания на одной странице.Ошибка 400 Плохой запрос Ajax Отправка SMTP-Email

Я следил за многими примерами в Интернете, но не могу показаться Франкенштейну всем этим, чтобы он работал для меня. Я считаю, что проблема заключается в получении данных из формы.

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 (Плохой запрос)»

Если кто-то может указать мне в правильном направлении, я бы очень признателен! Спасибо за чтение!

+0

Поскольку это ваш код, который устанавливает ответ 400, вам необходимо проверить, какие из ваших условий не работают. – Synchro

+0

Спасибо за подсказку @Synchro, я получил ее сейчас, после передачи «данных» в фигурных скобках ajax. – efettero

ответ

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'); 
    }); 
}); 
Смежные вопросы