为什么我的 AJAX 联系表单不会停留在同一页面上?

问题描述 投票:0回答:1

我的网站上有一个联系表格,是我 5 年前建立的。我记得它曾经直接在 #form-messages div 的页面上显示错误/成功消息,但现在它将页面更改为 send.php,显示未格式化的文本,而不是停留在联系表单页面上并在那里输出,我一生都无法弄清楚为什么。

event.preventDefault();
不应该阻止更改页面的默认行为吗?

这是相关的 HTML:

<form id="ajax-contact" method="post" action="send.php">
    <div class="field">
        <label for="name">Name</label>
        <input type="text" id="name" name="name" autocomplete="name" required>
    </div>

    <div class="field">
        <label for="email">Email</label>
        <input type="email" id="email" name="email" autocomplete="email" required>
    </div>

    <div class="field">
        <label for="message">Message</label>
        <textarea id="message" name="message" required></textarea>
    </div>
    <div class="field">
        <button type="submit" class="button g-recaptcha" data-sitekey="X" data-callback='onSubmit' data-action='submit'>Send</button>
    </div>
</form>
<div id="form-messages"></div>

这是 contact.js:

$(function() {
    // Get the form.
    var form = $('#ajax-contact');

    // Get the messages div.
    var formMessages = $('#form-messages');

    // 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,
            captcha: grecaptcha.getResponse()

        }).done(function(response) {
            // Make sure that the formMessages div has the 'success' class.
            formMessages.removeClass('error');
            formMessages.addClass('success');

            // Set the message text.
            if (data.responseText !== '') {
                formMessages.text(data.responseText);
            } else {
                formMessages.text('Oops! An error occurred and your message could not be sent.');
            }

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

            // Set the message text.
            if (data.responseText !== '') {
                formMessages.text(data.responseText);
            } else {
                formMessages.text('Oops! An error occurred and your message could not be sent.');
            }
        });
    });
});

这是 send.php:

<?php
// If the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // If the Google Recaptcha box was clicked
    if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
        $captcha=$_POST['g-recaptcha-response'];
        $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=X&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
        $obj = json_decode($response);

        // If the Google Recaptcha check was successful
        if($obj->success == true) {
          // Clean up the data
          $name = strip_tags(trim($_POST["name"]));
          $name = str_replace(array("\r","\n"),array(" "," "),$name);
          $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
          $message = trim($_POST["message"]);

          // Check for empty fields
          if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            http_response_code(400);
            echo "Oops! There was a problem with your submission. Please complete the form and try again.";
            exit;
          }

          // Set up the email to me
          $email_sender = "[email protected]";
          $email_receiver = "[email protected]";
          $subject = "New message from $name";
          $email_content = "Name: $name\nEmail: $email\n\nMessage:\n$message\n";
          $email_headers = "From: $name <$email_sender>" . "\r\n" . "Reply-To: $name <$email>";

          // Set up the confirmation email
          $confirm_content =  "Hi $name,\n\nI'll get back to you as soon as I can. For your convenience, here is a copy of the message you sent:\n\n----------\n\n$message\n";
          $confirm_headers = "From: My Name <$email_sender>"  . "\r\n" . "Reply-To: My Name <$email_receiver>";

          // Send the email to me
          if (mail($email_receiver, $subject, $email_content, $email_headers)) {
            http_response_code(200);
            echo "Thank You! Your message has been sent, and you should have received a confirmation email. I'll get back to you as soon as I can!";
            // Send the confirmation email
            mail($email, "Thank you for your message!", $confirm_content, $confirm_headers);
          } 
          // If the server was unable to send the mail
          else {
            http_response_code(500);
            echo "Oops! Something went wrong, and we couldn't send your message. Please try again.";
          }
      } 
      // If the Google Recaptcha check was not successful    
      else {
        http_response_code(400);
        echo "Robot verification failed. Please try again.";
      }
  } 
  // If the Google Recaptcha box was not clicked   
  else {
    http_response_code(400);
    echo "Please click the reCAPTCHA box.";
  }      
} 
// If the form was not submitted
// Not a POST request, set a 403 (forbidden) response code.         
else {
  http_response_code(403);
  echo "There was a problem with your submission, please try again.";
}      
?>
javascript php html jquery ajax
1个回答
0
投票

问题似乎出在验证码的实现上。我最初遵循 Google 自己的建议“将挑战绑定到提交按钮”,这似乎阻止了我阻止该按钮的默认行为。我最终放弃了尝试使用不可见的 reCAPTCHA 并返回到复选框实现,我终于让它工作了。 我的send.php没有改变。

我在 HTML 中所做的主要更改是验证码现在附加到空 div 而不是提交按钮:

<form id="ajax-contact" method="post" action="send.php"> <div class="field"> <label for="name">Name</label> <input type="text" id="name" name="name" autocomplete="name" required> </div> <div class="field"> <label for="email">Email</label> <input type="email" id="email" name="email" autocomplete="email" required> </div> <div class="field"> <label for="message">Message</label> <textarea id="message" name="message" required></textarea> </div> <div id="recaptcha" class="g-recaptcha" data-sitekey="x"></div> <div id="form-messages"></div> <div class="field"> <button id="contact-submit" type="submit" class="button">Send</button> </div> </form>

我的 contact.js 几乎完全没有改变,除了我在 
.done

部分设置消息文本的方式:

$(function() {
    var form = $('#ajax-contact');
    var formMessages = $('#form-messages');

    // Set up an event listener for the contact form.
    form.submit(function(event) {
        // Stop the default behavior 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,
            captcha: grecaptcha.getResponse()
        }).done(function(response) {
            // 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('');
            $('#message').val('');
        }).fail(function(data) {
            // Make sure that the formMessages div has the 'error' class.
            formMessages.removeClass('success');
            formMessages.addClass('error');

            // Set the message text.
            if (data.responseText !== '') {
                formMessages.text(data.responseText);
            } else {
                formMessages.text('Oops! An error occurred and your message could not be sent.');
            }
        });
    });
});

© www.soinside.com 2019 - 2024. All rights reserved.