You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ajax联系表单提交后跳转页面问题求助

Ajax联系表单跳转问题排查与修复

问题概述

5年前搭建的Ajax联系表单,原本提交后会在页面的#form-messages容器内显示错误或成功提示,但现在提交后直接跳转到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 = "myname@mydomain.com";
          $email_receiver = "myname@gmail.com";
          $subject = "New message from $name";
          $email_content = "Name: $name
Email: $email

Message:
$message
";
          $email_headers = "From: $name <$email_sender>" . "\r\n" . "Reply-To: $name <$email>";

          // Set up the confirmation email
          $confirm_content =  "Hi $name,

I'll get back to you as soon as I can. For your convenience, here is a copy of the message you sent:

----------

$message
";
          $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.";
}      
?>

问题原因分析

  1. reCAPTCHA回调冲突:按钮使用了data-callback='onSubmit'但未定义该函数,reCAPTCHA验证通过后会自动触发默认表单提交,绕过了jQuery的submit事件中的event.preventDefault()。
  2. AJAX参数传递错误:captcha: grecaptcha.getResponse()未被合并到formData中,导致后端无法接收g-recaptcha-response参数,验证失败。
  3. 回调变量错误:done回调中误用未定义的data变量,正确参数应为response,导致成功状态下提示信息无法正常显示。

修复方案

1. 修复reCAPTCHA回调逻辑

修改按钮类型为button避免默认提交,同时定义onSubmit函数触发表单提交:

<button type="button" class="button g-recaptcha" data-sitekey="X" data-callback='onSubmit' data-action='submit'>Send</button>

在contact.js中添加回调函数:

function onSubmit() {
    $('#ajax-contact').submit();
}

2. 修正AJAX参数传递

将reCAPTCHA响应添加到表单数据中:

var formData = form.serialize();
formData += '&g-recaptcha-response=' + grecaptcha.getResponse();

3. 修正回调变量错误

将done回调中的data.responseText改为response:

.done(function(response) {
    formMessages.removeClass('error');
    formMessages.addClass('success');

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

    $('#name').val('');
    $('#email').val('');
    $('#message').val('');
    grecaptcha.reset(); // 重置reCAPTCHA
})

完整修复后的contact.js

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

    form.submit(function(event) {
        event.preventDefault();

        var formData = form.serialize();
        formData += '&g-recaptcha-response=' + grecaptcha.getResponse();

        $.ajax({
            type: 'POST',
            url: form.attr('action'),
            data: formData
        }).done(function(response) {
            formMessages.removeClass('error');
            formMessages.addClass('success');

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

            $('#name').val('');
            $('#email').val('');
            $('#message').val('');
            grecaptcha.reset();
        }).fail(function(data) {
            formMessages.removeClass('success');
            formMessages.addClass('error');

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

function onSubmit() {
    $('#ajax-contact').submit();
}

额外检查项

  • 确认jQuery库已正确加载,版本兼容。
  • 查看浏览器控制台,排查grecaptcha未定义等JS报错。

内容的提问来源于stack exchange,提问作者kookiekween99

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 09:20:04