php 为什么我的AJAX联系表单不能保持在同一页面上?

mzmfm0qo  于 5个月前  发布在  PHP
关注(0)|答案(1)|浏览(75)

我在我的网站上有一个联系人表单,我最初是在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.";
}      
?>

7uzetpgm

7uzetpgm1#

这个问题似乎是在验证码实现中。我最初遵循Google自己的bind the challenge to the submit button建议,这似乎阻止了我阻止该按钮的默认行为。我最终放弃了尝试使用不可见的reCAPTCHA,并返回到复选框实现,我终于让它工作了。
我的send.php没有变化。
我在HTML中所做的主要更改是,captcha现在附加到一个空的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.');
            }
        });
    });
});

相关问题