【问题标题】:AJAX call in Wordpress on submit提交时在 Wordpress 中调用 AJAX
【发布时间】:2020-10-16 14:49:02
【问题描述】:

我从不使用 wordpress,所以我完全迷失了……我有一个 wordpress 网站,其中包含使用“contact-form-7”插件创建的表单……我需要进行 ajax 调用来发送表单当用户在网站上提交其中一个表单时,将数据发送到外部 URLe...我该怎么办?

我的 ajax 调用:

$.ajax({
  method: 'post',
  url: "external url",
  data: JSON.stringify({
          "env": "",
          "application": "",
          "operation": "",
          "token": "",
          "utente": "",
          "param": "",
       "data":{ DATA FROM FORM }
        }),
  dataType: 'json',
  },
  error: function(message) {
      
  }

【问题讨论】:

    标签: ajax wordpress contact-form-7


    【解决方案1】:

    您可以使用“wpcf7_before_send_mail”过滤器将联系表单7 提交的数据发送到使用 CURL 或 wp_remote_post 的任何网站。

       add_action( 'wpcf7_before_send_mail*', 'wpcf7_submite_data_to_3rdparty' );
        
        function wpcf7_submite_data_to_3rdparty( $contact_form ) {
            global $wpdb;
        
        if ( ! isset( $contact_form->posted_data ) && class_exists( 'WPCF7_Submission' ) ) {
            $submission = WPCF7_Submission::get_instance();
        
            if ( $submission ) {
                $form_data = $submission->get_posted_data();
            }
        } else {
            return '';
        }
        
        $body = array(        
            'name' => $form_data['name'],
            'email' => $form_data['email'],
            'comments' => $form_data['comments'],
        );
        
        $url = 'https://example.com';
        
        $params = array(
            'headers' => array(
                'Content-Type' => 'application/x-www-form-urlencoded'
            ),
            'body' => $body
        );
        
            $response = wp_remote_post( $url,  $params );
            
        }
    

    要处理 Jquery 事件,您可以使用事件监听器。

    document.addEventListener( 'wpcf7mailsent', function( event ) {
        console.log('mail sent OK');
        // Stuff
    }, false ); 
    

    wpcf7mailsent 当 Ajax 表单提交成功完成并发送邮件时触发。 wpcf7submit 当 Ajax 表单提交成功完成时触发,与其他事件无关。

    【讨论】:

    • 你为什么打电话给$wpdb? 另外,为什么return $contact_form 在第12 行?这些似乎都没有必要。由于这是一个钩子而不是过滤器,因此您只需 return 即可退出。所以你应该使用add_action 而不是add_filter
    猜你喜欢
    • 2013-09-17
    • 1970-01-01
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    • 2017-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多