Reputation: 17429
I use the following code in order to know if some username is already present in my database. I'm using jquery validator, and I configure the script in this way:
$(document).ready(function(){
// Validate
// http://bassistance.de/jquery-plugins/jquery-plugin-validation/
// http://docs.jquery.com/Plugins/Validation/
// http://docs.jquery.com/Plugins/Validation/validate#toptions
$('#profile').validate({
rules: {
name: {
minlength: 2,
required: true
},
username: {
minlength: 2,
required: true,
remote: "../check-username.php"
}
},
highlight: function(element) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
success: function(element) {
element
.text('OK!').addClass('valid')
.closest('.control-group').removeClass('error').addClass('success');
}
});
});
where check-username.php is defined as:
<?php
require_once('connection.php');
$check = "true";
$request = trim(strtolower($_REQUEST['username']));
mysql_select_db($dbname, $temp);
$query_username=sprintf("SELECT * FROM users WHERE username = '$request'");
$resultUsers = mysql_query($query_username, $temp) or die(mysql_error());
$usernameFound= mysql_num_rows($resultUsers);
if ($usernameFound> 0) {
$check = "false";
}
header("Content-type: application/json; charset=windows-1251");
$result = $_REQUEST['username'].'('.$check.')';
echo $result;
?>
All works good, except the recognition of already existing username. Maybe something is wrong in:
remote: "../check-username.php"
or in the php file itself.
Someone can help me?
EDIT 1:
Trying the @MHR code I obtain this:
In this case "user1" already exists in my database. So this is good, but I don't want that the output is written under my input.
Upvotes: 0
Views: 339
Reputation: 39270
http://docs.jquery.com/Plugins/Validation/Methods/remote
The documentation has a shiningly absent example of what the response must be but it hints at JSON:
The response is evaluated as JSON and must be true for valid elements, and can be any false, undefined or null for invalid elements, using the default message; or a string, eg. "That name is already taken, try peter123 instead" to display as the error message. For more examples, take a look the marketo demo and the milk demo.
My guess is that you should return "true" if it's valid and "false" if it isn;t:
$check = true;
$request = trim(strtolower($_REQUEST['username']));
mysql_select_db($dbname, $temp);
$query_username=sprintf("SELECT * FROM users WHERE username = '$request'");
$resultUsers = mysql_query($query_username, $temp) or die(mysql_error());
$usernameFound= mysql_num_rows($resultUsers);
if ($usernameFound> 0) {
$check = false;
}
header("Content-type: application/json; charset=windows-1251");
if($check){
$check = "true";
}else{
$check = "User: ".$request." already exist, please choose another user name.";
}
$result = "\"".$check."\"";
echo $result;
Upvotes: 2