In this question, a user attempts to validate a username's existence using jQuery.validate's remote method. However, they encounter an issue where the validation always fails, even when the username is not taken.
jQuery: $("#signupForm").validate({ rules: { username: { required: true, minlength: 3, remote: "check-username.php" } }, messages: { username: { remote: "This username is already taken! Try another." } } }); check-username.php: <?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 original code used the remote method incorrectly, as it always returned true, indicating that the username was taken.
The user resolved the issue by updating their PHP code as follows:
<?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 updated PHP code:
The above is the detailed content of Why Does My jQuery Validate Remote Method Always Fail When Checking Username Availability?. For more information, please follow other related articles on the PHP Chinese website!