【问题标题】:Check if email exists in Wordpress through Ajax on HTML form submision通过 HTML 表单提交中的 Ajax 检查 Wordpress 中是否存在电子邮件
【发布时间】:2021-12-27 15:31:52
【问题描述】:

在我的 WordPress v5.8.2 中,我在 functions.php 中本地化了 ajax_url

wp_enqueue_script('site_scripts', get_stylesheet_directory_uri() . '/assets/js/site-scripts.js', array('jquery'), null, true);

wp_localize_script('site_scripts', 'site_ajax', array('ajax_url' => admin_url('admin-ajax.php'), 'check_nonce' => wp_create_nonce('site_ajax_nonce')));

使用下面的 jQuery 脚本,我正在处理表单以检查 HTML 表单中的电子邮件 ID 是否已存在于 WordPress 中:

   $(document).on("submit", "#form", function(e) {
     e.preventDefault();
     $email = $(this).find('input[name=email]').val(); // email
     //ajax request, check if user exists
     $.ajax({
       type: "GET",
       dataType: 'json',
       url: site_ajax.ajax_url,
       data: {
         email: $email,
         action: 'email_exists_check',
         security: site_ajax.site_ajax_nonce
       },
       success: function(data) {
         if (data.result) {
           alert('Email exists!');
         } else {
           alert('Email does not exists!');
         }
       }
     });
   });

在单独文件中的 PHP 代码下方检查电子邮件:

add_action('wp_ajax_email_exists_check', 'email_exists_check');
add_action('wp_ajax_nopriv_email_exists_check', 'email_exists_check');

function email_exists_check() {

    // Check nonce and email is set by ajax post.
    if (isset($_POST['email']) && wp_verify_nonce('check_nonce', 'security')) {
        // Sanitize your input.
        $email = sanitize_text_field(wp_unslash($_POST['email']));
        // do check.
        if (email_exists($email)) {
            $response = true;
        } else {
            $response = false;
        }
        // send json and exit.
        wp_send_json($response);
    }
}

如果电子邮件存在,上述整个代码无法发出警报。

我怎样才能使这段代码工作?

更新 #1

根据@Howard E 的建议,我发现包含email_exists_check() 函数的PHP 文件没有加载。

现在 PHP 文件已加载,我没有得到实际的 email_exists 状态。对于存在和不存在的电子邮件,警报始终为电子邮件不存在 (data.result == false)。

似乎email_exists_check 函数本身没有加载。我用下面的代码检查了日志,响应为 undefined 或 0:

 success: function (json) {
     console.log(json);
 }

【问题讨论】:

    标签: php jquery ajax wordpress


    【解决方案1】:

    将你的脚本加入队列并本地化添加到functions.php:

    add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_scripts' );
    
    function my_theme_enqueue_scripts() {
        wp_enqueue_script( 'site_scripts', get_stylesheet_directory_uri() . '/scripts.js', array( 'jquery' ), '1.0', true );
    
        wp_localize_script(
            'site_scripts',
            'site_ajax',
            array(
                'ajax_url'    => admin_url( 'admin-ajax.php' ),
                'check_nonce' => wp_create_nonce( 'site_ajax_nonce' ),
            )
        );
    
    }
    
    add_action('wp_ajax_email_exists_check', 'email_exists_check');
    add_action('wp_ajax_nopriv_email_exists_check', 'email_exists_check');
    
    function email_exists_check() {
        // Check nonce and email is set by ajax post.
        if ( isset( $_POST['email'] ) && wp_verify_nonce( 'check_nonce', 'security' ) ) {
            // Sanitize your input.
            $email = sanitize_text_field( wp_unslash( $_POST['email'] ) );
            // do check.
            if ( email_exists( $email ) ) {
                $response = true;
            } else {
                $response = false;
            }
            // send json and exit.
            wp_send_json( $response );
        }
    }
    

    还有你的 jQuery:

    $( document ).on(  "submit",  "#form",  function(e) {
        e.preventDefault();
        $email = $( this ).find( 'input[name=email]' ).val(); // email
        // ajax request, check if user exists.
        $.ajax({
            type: "POST",
            dataType: 'json',
            url: site_ajax.ajax_url,
            data: {
                email: $email,
                action: 'email_exists_check',
                security: site_ajax.check_nonce
                }
            })
            .done(function(data) {
                if (data.result) {
                    alert( 'Email exists!' );
                } else {
                    alert( 'Email doesn\'t exsist!' );
                }
            });
    });
    

    【讨论】:

    • 在控制台中,我有这个错误Uncaught ReferenceError: site_ajax is not defined 指的是$.ajax 中的url
    • 检查您的 localize_script 和 enqueue_script 是否正确。这是它不会被定义的唯一原因。
    • 查看更新 #2
    • 好的。那么问题出在哪里?
    • 无论邮件是否存在,我都没有收到回复,这是主要问题。
    【解决方案2】:

    尝试像这样解析 JSON 响应:

     $(document).on("submit", "#form", function(e) {
         e.preventDefault();
         $email = $(this).find('input[name=email]').val(); // email
         //ajax request, check if user exists
         $.ajax({
            type: "GET",
            dataType: 'json',
            url: site_ajax.ajax_url,
            data: {
                action: 'email_exists_check',
                security: site_ajax.site_ajax_nonce
            },
            success: function(data) {
                var status = JSON.parse(data);
                if (status.result === true) {
                    alert('Email exists!');
                } else {
                    alert('Email doesn\t exsists!');
                }
            }
        });
    });
    

    另外,不要忘记在 WordPress 中进行 AJAX 调用后的die()

    <?php 
    add_action('wp_ajax_email_exists_check', 'email_exists_check');
    add_action('wp_ajax_nopriv_email_exists_check', 'email_exists_check');
    
    function email_exists_check() {
    
        $response = array();
        $email = $_GET['email'];
    
        // do check
        if ( email_exists( $email ) ) {
            $response['result'] = true;
        } else {
            $response['result'] = false;
        }
    
        // echo json
        echo json_encode( $response );
        die();
    }
    

    【讨论】:

    • 这给了我一个 Failed to load resource: the server responded with a status of 400 (Bad Request) 的错误,并且 URL 是 ...../wp-admin/admin-ajax.php?action=email_exists_check 和 0。
    • 0 响应是因为您没有将 die() 放在 AJAX 调用的末尾
    • 尝试了所有 wp_die();die();exit();,但没有成功。
    【解决方案3】:

    wp_verify_nonce 导致了问题。

    这就是我修改代码的方式,并且在所有方面都按预期工作:

    $(document).on("submit", "#form", function(e) {
         e.preventDefault();
         $email = $(this).find('input[name=email]').val(); // email
         //ajax request, check if user exists
         $.ajax({
           type: "GET",
           dataType: 'json',
           url: site_ajax.ajax_url,
           data: {
             email: $email,
             action: 'email_exists_check',
             check_nonce: site_ajax.check_nonce
           },
           success: function(data) {
             if (data.result) {
               alert('Email exists!');
             } else {
               alert('Email does not exists!');
             }
           }
         });
       });
    

    注意在data: 中将security 替换为check_nonce

    PHP 代码下方:

    add_action('wp_ajax_email_exists_check', 'email_exists_check');
    add_action('wp_ajax_nopriv_email_exists_check', 'email_exists_check');
    
    function email_exists_check() {
        // Check nonce and email is set by ajax post.
        if (wp_verify_nonce($_POST['check_nonce'], 'site_ajax_nonce')) {
            // Sanitize your input.
            $email = sanitize_text_field(wp_unslash($_POST['email']));
            // do check.
            if (email_exists($email)) {
                $response = true;
            } else {
                $response = false;
            }
            // send json and exit.
            wp_send_json($response);
        }
    }
    

    注意if (wp_verify_nonce){} 语句和nonce 的使用。

    【讨论】:

      猜你喜欢
      • 2019-02-13
      • 2018-10-13
      • 1970-01-01
      • 1970-01-01
      • 2012-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-05
      相关资源
      最近更新 更多