Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Remote validation

I have a problem with jQuery remote validation. I am checking if email is registered, remote validation works, but it display only values - true or false and I cant submit the form than.

jQuery code :

$("#form").validate({
  rules: {
    email: {
      required: true,
      email: true,
      remote: "check-email.php"

    }
  }
}); 

check-mail.php code :

$email = trim(strtolower($_REQUEST['email']));


$checkemail = mysql_query("SELECT * FROM users WHERE email = '".$email."'");  

if(mysql_num_rows($checkemail) == 1)
{
$valid = 'false';
}
else
{
$valid = 'true';
} //end of $checkemail if statemant


echo json_encode($valid);
like image 642
iKaspars Avatar asked Mar 03 '11 07:03

iKaspars


1 Answers

$checkemail = mysql_query("SELECT * FROM users WHERE email = '".$email."'");  

Never ever ever ever do this. This is asking for trouble: SQL injection, random errors (the single quote is valid in email addresses, BTW).

There are parameterized queries, use them. It's only a few lines more of code, but it is the difference between a security flaw as wide as a barn door and a safe database interaction.

if(mysql_num_rows($checkemail) == 1)
{
$valid = 'false';
}
else
{
$valid = 'true';
}

is a very verbose way of saying

$valid = mysql_num_rows($checkemail) == 1;

According to the docs, the response of remote validation is a JSON-encoded boolean, not a JSON-encoded string.

You have "true" or "false", which will become "\"true\"" or "\"false\"" through json_encode(), which is wrong. Actual true or false will become "true" or "false", which is correct.

Setting the response content type to JSON might also be a good idea:

header('Content-type: application/json');
like image 65
Tomalak Avatar answered Sep 28 '22 00:09

Tomalak