在 HTML 表单提交时通过 Ajax 检查 Wordpress 中是否存在电子邮件

Check if email exists in Wordpress through Ajax on HTML form submision

在我的 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 函数本身没有加载。我用下面的代码检查了日志,响应未定义或 0:

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

尝试像这样解析 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!');
            }
        }
    });
});

此外,在 AJAX 调用 WordPress

后,不要忘记 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();
}

排队您的脚本并本地化添加到 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!' );
            }
        });
});

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的使用。