jQuery AJAX错误处理问题


jQuery AJAX error handling issue

我正在制作一个表单,该表单在成功时将显示带有成功或失败文本的引导模式。我面临的问题是,我的成功部分正在工作,模式显示成功消息,但失败部分显示模式,但为空,它缺少错误文本。我似乎没有发现问题,也许是因为我已经看了很长时间了。任何帮助都将不胜感激。

代码如下:HTML:

<form id="ajax-contact" method="post" action="mail.php">
                              <div class="form-group">
                                <label for="name">Name:</label>
                                <input type="text" class="form-control msg" id="name" name="name" placeholder="Your name..." required>
                              </div>
                              <div class="form-group">
                                <label for="email">Email:</label>
                                <input type="email" class="form-control msg" id="email" name="email" placeholder="Your email address..." required>
                              </div>
                              <div class="form-group">
                                <label for="select">Category:</label>
                                <select class="form-control msg" id="select" name="select" required>
                                  <option value="">Select a category</option>
                                  <option value="Website building">Website building</option>
                                  <option value="Template creation">Template creation</option>
                                  <option value="Logo Design">Logo Design</option>
                                  <option value="Mobile App">Mobile App</option>
                                  <option value="SEO Services">SEO Services</option>
                                </select>
                              </div>
                              <div class="form-group">
                                <label for="subject">Subject:</label>
                                <input type="text" class="form-control msg" id="subject" name="subject" placeholder="Message subject..." required>
                              </div>
                              <div class="form-group">
                                <label for="message">Message:</label>
                                <textarea class="form-control" rows="5" id="message" name="message" placeholder="Type your message here..." required></textarea>
                              </div>
                  <!-- Modal -->
                   <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
                    <div class="modal-dialog" role="document">
                     <div class="modal-content">
                      <div class="modal-body">
                       <h1 id="form-messages" class="text-center">
                       </h1>
                      </div>
                      <div class="modal-footer">
                       <button type="button" class="btn btn-default center-block modalBtn" data-dismiss="modal">Close</button>
                      </div>
                     </div>
                    </div>
                   </div>
                  <button type="submit" class="btn btn-default msg-button" data-toggle="modal" data-target="#myModal">Submit</button>
                             </form>

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 = strip_tags(trim($_POST["subject"]));
    $subject = str_replace(array("'r","'n"),array(" "," "),$subject);
    $select = trim($_POST["select"]);
    $message = trim($_POST["message"]);
    // Check that data was sent to the mailer.
    if (empty($name) OR empty($message) OR empty($subject) OR empty($select) 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;
    }
    // Set the recipient email address.
    // FIXME: Update this to your desired email address.
    $recipient = "info@email.com";
    // Build the email content.
    $email_content = "Name: $name'n";
    $email_content .= "Email: $email'n";
    $email_content .= "Category: $select'n";
    $email_content .= "Subject: $subject'n'n";
    $email_content .= "Message: $message'n";
    // Build the email headers.
    $email_headers = "From: $name <$email>";
    // Send the email.
    if (mail($recipient, $subject, $email_content, $email_headers)) {
        // 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.";
}

?>

Jquery:

$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// TODO: The rest of the code will go here...
// Set up an event listener for the contact form.
$(form).submit(function(event) {
    // Stop the browser from submitting the form.
    event.preventDefault();
    // Serialize the form data.
    var formData = $(form).serialize();
    // Submit the form using AJAX.
    $.ajax({
        type: 'POST',
        url: $(form).attr('action'),
        data: formData,
        success: function(response) {
            // Make sure that the formMessages div has the 'success' class.
            $(formMessages).removeClass('error');
            $(formMessages).addClass('success');
            console.log(response);
            // Set the message text.
            $(formMessages).text(response);
            // Clear the form.
            $('#name').val('');
            $('#email').val('');
            $('#select').val('');
            $('#subject').val('');
            $('#message').val('');
        },
        error: function(textStatus) {
            alert("asd");
            // Make sure that the formMessages div has the 'error' class.
            $(formMessages).removeClass('success');
            $(formMessages).addClass('error');
            console.log(textStatus);
            // Set the message text.
            if (textStatus !== '') {
                $(formMessages).text(textStatus);
            } else {
                $(formMessages).text('Oops! An error occured and your message could not be sent.');
            }
        }
    });
});
});

更改

$(form).submit(function(event) {

$(form).find('[type="submit"]').click(function(event) {

你会得到

// Oops! There was a problem with your submission. Please complete the form and try again.

问题是你使用的是表单标签,HTML5不允许提交表单,直到所有必填字段都填写完毕,所以你的表单一开始就没有提交。