Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery check mysql database if username is already taken

i know that this is possible but i am confused as to how it works. I have been looking online for how it is done and I think i am missing something in the process

I have this jQuery code so far:

$("#Contact_Info").validate({  
        rules: {
            username: {
                required: true,
                minlength: 6,
                remote: "check-username.php"
                }
            },
        messages: {
            username:{
                remote: "This username is already taken! Try another."
            }
        }
  });

How should i write my php page to make it talk to the jQuery code?

So far I have:

$name = mysql_real_escape_string($name);

$query = "SELECT USERNAME FROM T_MEMBER WHERE USERNAME='$name';";
$res = mysql_query($query);
if (mysql_num_rows($res) > 0) {
   return false;
} else
   return true; 

How do I get the $name variable from the javascript? Do i have to set the "remote" to be POST?

Thanks in advance, Ian McCullough

like image 810
Ian McCullough Avatar asked Oct 14 '22 14:10

Ian McCullough


1 Answers

Your PHP page communicates back to the Javascript just through outputting the data. Depending on the plugin, you could achieve a true/false by echoing 1 or 0, or perhaps even the string true or false

The manual says:

The response is evaluated as JSON and must be true for valid elements, and can be any false, undefined or null for invalid elements

So you can change your PHP to this:

if (mysql_num_rows($res) > 0) {
    $output = true;
} else {
    $output = false;
}
echo json_encode($output);
like image 155
nickf Avatar answered Oct 18 '22 14:10

nickf