jQuery Validate Remote Method for Username Availability Checking
How can you utilize the remote method in jQuery Validate to verify if a username exists in a database?
Scenario:
Consider the following scenario:
$("#signupForm").validate({ rules: { username: { required: true, minlength: 3, remote: "check-username.php" } }, messages: { username: { remote: "This username is already taken! Try another." } } });
<?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); ?>
Problem:
Despite the code above, the username field always displays an error, even when the username is not in the database.
Solution:
The original PHP code was ineffective in verifying username availability. The following modified version resolves the issue:
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 above is the detailed content of How to Use jQuery Validate's Remote Method for Username Availability Checking?. For more information, please follow other related articles on the PHP Chinese website!