联系表格 7 提交功能不起作用

function on Contact Form 7 submission not working

我在 Wordpress 中使用 Contact Form 7,我想做的是在提交我创建的表单时调用特定的 JavaScript 函数,显示弹出窗口成功。这是我的代码

    add_action('wpcf7_mail_sent', function ($cf7) {
    // Run code after the email has been sent
 $wpcf = WPCF7_ContactForm::get_current();
$wpccfid=$wpcf->id;
    // if you wanna check the ID of the Form $wpcf->id
     if ( '3854' == $wpccfid ) { // Change 123 to the ID of the form 
echo '
 <div class="modal" id="myModal2" role="dialog" style="display:block;" tabindex="-1">
    <div class="modal-dialog">
      <!-- Modal content-->
      <div class="modal-content no_pad text-center">
         <button type="button" class="close" data-dismiss="modal">&times;</button>
        <div class="modal-header heading">
          <h3 class="modal-title">Message Sent!</b></h3>
        </div>
        <div class="modal-body">

            <div class="thanku_outer define_float text-center">
                <h3>Thank you for getting in touch!</h3>
            </div>
        </div>
        <div class="modal-footer">
        </div>
      </div>

    </div>
    </div>
';
    }
});

我有一个错误,我不知道如何解决

在 Ajax 中调用了 wpcf7_mail_sent 函数,系统期望 Ajax 回复为 JSON。所以当你直接 echo 一些 HTML 时,会破坏 JSON 并且 Javascript 无法解析它。

我找不到任何允许自定义 HTML 代码的 wpcf7_mail_sent 用法示例,因此可能无法这样做。问题是代码 returns 一个 message JSON 变量,我认为这应该是纯文本,而不是 HTML.

备选方案 1:在 Javascript

中编辑 DOM

我见过的另一种方法是在 wpcf7mailsent 事件上使用 Javascript 而不是 PHP 和监听器。

参见下面的示例:

<script>
    document.addEventListener( 'wpcf7mailsent', function( event ) {
            // Your code to edit the HTML goes here
    }, false ); 
</script>

您可以在另一个答案中找到更多关于如何使用它以及如何获得 form_id 的信息:

备选方案 2:重定向

或者,您可以将用户重定向到自定义页面,而不是显示 Ajax 确认信息

<script>
document.addEventListener( 'wpcf7mailsent', function( event ) {
    if ( 'FORMID' === event.detail.contactFormId ) {
        location = 'REDIRECTURL';
    }
}, false );
</script>