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:
- First,
wp_signonruns with empty credentials and returns a WP_Error, so you echo the "Wrong username or password" JSON. - Then your empty field check runs and echoes another JSON string.
- 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
相关产品推荐
相关产品推荐

