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

mzmfm0qo  于 2024-01-05  发布在  PHP
关注(0)|答案(1)|浏览(208)

我在我的网站上有一个联系人表单,我最初是在5年前建立的。我记得它曾经直接在页面上的#form-messages div中显示错误/成功消息,但现在它将页面更改为send.php,显示无格式的文本,而不是停留在联系人表单页面并在那里输出,我一辈子也想不通为什么。难道event.preventDefault();不应该阻止改变页面的默认行为吗?
以下是相关的HTML:

  1. <form id="ajax-contact" method="post" action="send.php">
  2. <div class="field">
  3. <label for="name">Name</label>
  4. <input type="text" id="name" name="name" autocomplete="name" required>
  5. </div>
  6. <div class="field">
  7. <label for="email">Email</label>
  8. <input type="email" id="email" name="email" autocomplete="email" required>
  9. </div>
  10. <div class="field">
  11. <label for="message">Message</label>
  12. <textarea id="message" name="message" required></textarea>
  13. </div>
  14. <div class="field">
  15. <button type="submit" class="button g-recaptcha" data-sitekey="X" data-callback='onSubmit' data-action='submit'>Send</button>
  16. </div>
  17. </form>
  18. <div id="form-messages"></div>

字符串
以下是contact.js:

  1. $(function() {
  2. // Get the form.
  3. var form = $('#ajax-contact');
  4. // Get the messages div.
  5. var formMessages = $('#form-messages');
  6. // Set up an event listener for the contact form.
  7. form.submit(function(event) {
  8. // Stop the browser from submitting the form.
  9. event.preventDefault();
  10. // Serialize the form data.
  11. var formData = form.serialize();
  12. // Submit the form using AJAX.
  13. $.ajax({
  14. type: 'POST',
  15. url: form.attr('action'),
  16. data: formData,
  17. captcha: grecaptcha.getResponse()
  18. }).done(function(response) {
  19. // Make sure that the formMessages div has the 'success' class.
  20. formMessages.removeClass('error');
  21. formMessages.addClass('success');
  22. // Set the message text.
  23. if (data.responseText !== '') {
  24. formMessages.text(data.responseText);
  25. } else {
  26. formMessages.text('Oops! An error occurred and your message could not be sent.');
  27. }
  28. // Clear the form.
  29. $('#name').val('');
  30. $('#email').val('');
  31. $('#message').val('');
  32. }).fail(function(data) {
  33. // Make sure that the formMessages div has the 'error' class.
  34. formMessages.removeClass('success');
  35. formMessages.addClass('error');
  36. // Set the message text.
  37. if (data.responseText !== '') {
  38. formMessages.text(data.responseText);
  39. } else {
  40. formMessages.text('Oops! An error occurred and your message could not be sent.');
  41. }
  42. });
  43. });
  44. });


下面是send.php:

  1. <?php
  2. // If the form was submitted
  3. if ($_SERVER["REQUEST_METHOD"] == "POST") {
  4. // If the Google Recaptcha box was clicked
  5. if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
  6. $captcha=$_POST['g-recaptcha-response'];
  7. $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=X&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
  8. $obj = json_decode($response);
  9. // If the Google Recaptcha check was successful
  10. if($obj->success == true) {
  11. // Clean up the data
  12. $name = strip_tags(trim($_POST["name"]));
  13. $name = str_replace(array("\r","\n"),array(" "," "),$name);
  14. $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
  15. $message = trim($_POST["message"]);
  16. // Check for empty fields
  17. if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  18. http_response_code(400);
  19. echo "Oops! There was a problem with your submission. Please complete the form and try again.";
  20. exit;
  21. }
  22. // Set up the email to me
  23. $email_sender = "[email protected]";
  24. $email_receiver = "[email protected]";
  25. $subject = "New message from $name";
  26. $email_content = "Name: $name\nEmail: $email\n\nMessage:\n$message\n";
  27. $email_headers = "From: $name <$email_sender>" . "\r\n" . "Reply-To: $name <$email>";
  28. // Set up the confirmation email
  29. $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";
  30. $confirm_headers = "From: My Name <$email_sender>" . "\r\n" . "Reply-To: My Name <$email_receiver>";
  31. // Send the email to me
  32. if (mail($email_receiver, $subject, $email_content, $email_headers)) {
  33. http_response_code(200);
  34. 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!";
  35. // Send the confirmation email
  36. mail($email, "Thank you for your message!", $confirm_content, $confirm_headers);
  37. }
  38. // If the server was unable to send the mail
  39. else {
  40. http_response_code(500);
  41. echo "Oops! Something went wrong, and we couldn't send your message. Please try again.";
  42. }
  43. }
  44. // If the Google Recaptcha check was not successful
  45. else {
  46. http_response_code(400);
  47. echo "Robot verification failed. Please try again.";
  48. }
  49. }
  50. // If the Google Recaptcha box was not clicked
  51. else {
  52. http_response_code(400);
  53. echo "Please click the reCAPTCHA box.";
  54. }
  55. }
  56. // If the form was not submitted
  57. // Not a POST request, set a 403 (forbidden) response code.
  58. else {
  59. http_response_code(403);
  60. echo "There was a problem with your submission, please try again.";
  61. }
  62. ?>

7uzetpgm

7uzetpgm1#

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

  1. <form id="ajax-contact" method="post" action="send.php">
  2. <div class="field">
  3. <label for="name">Name</label>
  4. <input type="text" id="name" name="name" autocomplete="name" required>
  5. </div>
  6. <div class="field">
  7. <label for="email">Email</label>
  8. <input type="email" id="email" name="email" autocomplete="email" required>
  9. </div>
  10. <div class="field">
  11. <label for="message">Message</label>
  12. <textarea id="message" name="message" required></textarea>
  13. </div>
  14. <div id="recaptcha" class="g-recaptcha" data-sitekey="x"></div>
  15. <div id="form-messages"></div>
  16. <div class="field">
  17. <button id="contact-submit" type="submit" class="button">Send</button>
  18. </div>
  19. </form>

字符串
我的contact.js几乎完全不变,除了我在.done部分设置消息文本的方式:

  1. $(function() {
  2. var form = $('#ajax-contact');
  3. var formMessages = $('#form-messages');
  4. // Set up an event listener for the contact form.
  5. form.submit(function(event) {
  6. // Stop the default behavior from submitting the form.
  7. event.preventDefault();
  8. // Serialize the form data.
  9. var formData = form.serialize();
  10. // Submit the form using AJAX.
  11. $.ajax({
  12. type: 'POST',
  13. url: form.attr('action'),
  14. data: formData,
  15. captcha: grecaptcha.getResponse()
  16. }).done(function(response) {
  17. // Make sure that the formMessages div has the 'success' class.
  18. formMessages.removeClass('error');
  19. formMessages.addClass('success');
  20. // Set the message text.
  21. formMessages.text(response);
  22. // Clear the form.
  23. $('#name').val('');
  24. $('#email').val('');
  25. $('#message').val('');
  26. }).fail(function(data) {
  27. // Make sure that the formMessages div has the 'error' class.
  28. formMessages.removeClass('success');
  29. formMessages.addClass('error');
  30. // Set the message text.
  31. if (data.responseText !== '') {
  32. formMessages.text(data.responseText);
  33. } else {
  34. formMessages.text('Oops! An error occurred and your message could not be sent.');
  35. }
  36. });
  37. });
  38. });

展开查看全部

相关问题