Remote jQuery validation

I have a problem with remote jQuery validation. I check if the email is registered, the remote check works, but it displays only the values ​​- true or false, and I can not submit the form except.

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); 
+5
source share
3 answers
 $checkemail = mysql_query("SELECT * FROM users WHERE email = '".$email."'"); 

Never, never, ever do it. This is asking for problems : SQL injection, random errors (the only quote is valid in email addresses, BTW).

There are parameterized queries , use them. These are just a few lines of code, but this is the difference between a lack of security, like a barn door, and secure interaction with the database.

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

- a very verbose way to say

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

According to the docs, the remote verification response is logical rather than JSON-encoded JSON.

You have "true" or "false" which will become "\"true\"" or "\"false\"" via json_encode() , which is not true. Actual true or false will become "true" or "false" , which is true.

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

 header('Content-type: application/json'); 
+12
source

It could just be returning strings when a boolean value is required. Perhaps try the following:

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

For those people who cannot receive remote verification using the technique described above, follow my two cents that can help you in the right way.

1). It works only with v1.6.1 and higher. Stick to the latest jQuery version http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js

2). Choose "synchronous" remote execution, which is asynchronous by default. Set async to false.

 $("#form").validate({ rules: { email: { required: true, email: true, remote: { url:"check-email.php", async:false } } } }); 
+1
source

Source: https://habr.com/ru/post/945117/


All Articles