首页 > 解决方案 > 联系表格 7 提交上的功能不起作用

问题描述

我在 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>
';
    }
});

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

错误

标签: phpwordpressfunctionpluginscontact-form-7

解决方案


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

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

备选方案 1:在 Javascript 中编辑 DOM

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

请参见下面的示例:

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

form_id您可以在其他答案中找到有关如何使用它以及如何获取的更多信息: https ://stackoverflow.com/a/46977796/1529324

备选方案 2:重定向

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

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

推荐阅读