I’m using a basic registration form with AJAX, but the form is not connecting to the database. I’m obviously overlooking something.
So here’s the field I want to validate.
Username:<input type="text" name="user" id="user" maxlength="30">
<span id="msgbox" style="display:none"/></input>
Then I use jQuery, here’s the code:
$(document).ready(function() {
$("#user").blur(function() {
//remove all the class add the messagebox classes and start fading
$("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
//check the username exists or not from ajax
$.post("user_availability.php",{ user_name:$(this).val() },
function(data) {
if(data=='no') { //if username not avaiable
$("#msgbox").fadeTo(200,0.1,function() {//start fading the messagebox
//add message and change the class of the box and start fading
$(this).html('This User name Already exists').addClass('messageboxerror').fadeTo(900,1);
});
} else {
$("#msgbox").fadeTo(200,0.1,function() { //start fading the messagebox
//add message and change the class of the box and start fading
$(this).html('Username available to register').addClass('messageboxok').fadeTo(900,1);
});
} // else
} // function
); // $.post
}); // blur
}); // ready
And I have this code, user_availability.php:
mysql_connect(localhost,$user,$password);
or die('There is error to connect to server:-'.mysqli_connect_error());
$db_selected = mysql_select_db($database);
$user_name=$_POST['user_name'];
$sql = "select * from members where username='$user_name'";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result))
{
$existing_users[] = $row['username'];
}
if (in_array($user_name, $existing_users))
{
echo "no"; //user name is not availble
}
else
{
echo "yes"; //user name is available
}
I get no database errors. The form will be more substantial, but I can’t get it to work with this field. Any suggestions?
Just a nitpick on the select statement. Since you only need to get how many rows exist for the entered username you don’t need to do a “select *” as depending on the number of columns in your users table you could be returning quite a bit of data. I would revise your query to be like so:
Then you check to make sure that the result of the query equals zero. If it does then the username is available.
I know that the above wasn’t an answer to your question but just thought I would point it out since this looks to be a function that is going to get called a lot depending on the traffic on your registration form and the creativity of your visitors.