You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress自定义AJAX登录表单:如何检测用户名或密码字段为空并显示对应错误提示

Fixing the AJAX Login Empty Field Validation Issue

Hey there, let's figure out why your login form gets stuck on loading when fields are empty! The problem comes down to code order and duplicate JSON output—here's how to fix it step by step:

What Went Wrong

Your empty field check was placed after the wp_signon logic. When a user submits empty fields:

  1. First, wp_signon runs with empty credentials and returns a WP_Error, so you echo the "Wrong username or password" JSON.
  2. Then your empty field check runs and echoes another JSON string.
  3. The frontend gets two conflicting JSON responses it can't parse, so it stays stuck on loading indefinitely.

Corrected Code

Here's the fixed ajax_login function with proper validation flow and cleanup:

/* Ajax Form Login - Function 2 */
function ajax_login() {
    // First check nonce - terminate if validation fails
    check_ajax_referer( 'ajax-login-nonce', 'security' );

    // Step 1: Check for empty fields FIRST, before login attempts
    if( empty($_POST['username']) || empty($_POST['password']) ) {
        echo json_encode(array(
            'loggedin' => false, 
            'message' => __('您必须输入用户名和密码才能登录。')
        ));
        die(); // Stop execution immediately after sending the error response
    }

    // Step 2: Only proceed if fields are filled, then handle login logic
    $info = array();
    $info['user_login'] = $_POST['username'];
    $info['user_password'] = $_POST['password'];
    $info['remember'] = true;

    $user_signon = wp_signon( $info, false );
    if ( is_wp_error($user_signon) ){
        echo json_encode(array(
            'loggedin' => false, 
            'message' => __('Wrong username or password.')
        ));
    } else {
        echo json_encode(array(
            'loggedin' => true, 
            'message' => __('Login successful, redirecting...')
        ));
    }
    die(); // Ensure no extra output gets appended to the JSON response
}

Key Improvements

  • Moved empty field validation to the top: We check for empty inputs before even attempting to log the user in—this is more efficient and ensures the correct error message takes priority.
  • Added die() after the empty field error: This stops the function from running any further code once we've sent the empty field response, preventing duplicate JSON outputs.
  • Retained die() at the end: Guarantees no extra whitespace or unintended code gets added to the response, which would break frontend JSON parsing.

Now when users submit empty fields, they'll see the proper "您必须输入用户名和密码才能登录" message, and the form won't get stuck on loading anymore.

内容的提问来源于stack exchange,提问作者Snorlax

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 16:59:05