When attempting to validate a username's existence in a database using jQuery.validate, the error is always triggered, indicating that the username is already taken, even if it's not. The problem arises with the PHP code used for validation.
The initial implementation utilized the following jQuery code:
$("#signupForm").validate({ rules: { username: { required: true, minlength: 3, remote: "check-username.php", }, }, messages: { username: { remote: "This username is already taken! Try another.", }, }, });
And the following PHP script for validation:
<?php require_once "./source/includes/data.php"; header('Content-type: application/json'); $name = mysql_real_escape_string($_POST['username']); $check_for_username = mysql_query("SELECT username FROM mmh_user_info WHERE username='$name'"); if (mysql_num_rows($check_for_username) > 0) { $output = true; } else { $output = false; } echo json_encode($output); ?>
The issue was resolved by revising the PHP script. The modified code:
<?php require_once "./source/includes/data.php"; header('Content-type: application/json'); $request = $_REQUEST['username']; $query = mysql_query("SELECT * FROM mmh_user_info WHERE username ='$username'"); $result = mysql_num_rows($query); if ($result == 0){ $valid = 'true';} else{ $valid = 'false'; } echo $valid; ?>
The initial PHP code used mysql_real_escape_string to sanitize the $name variable. However, a more comprehensive approach to sanitizing the input was required. Additionally, the if-else statement's logic was inverted to produce the correct response: if ($result != 0) would have indicated that the username exists.
The above is the detailed content of Why Does My jQuery Validate Remote Method Always Indicate Username Availability?. For more information, please follow other related articles on the PHP Chinese website!