I'm having some strange problems using the validation plugin with jquery. This seems to have been asked a few times, but i cannot find the answer to my problem. I've got a form, and I am trying to see if the email has already been entered - if it has, the user should not be able to submit the form. I'm using FirePHP to output various variables. This is where I notice that the return value of my query is always "1" (which is wrong). However, when I manually query my db (using PhpMyAdmin), the correct answer ("0") comes up.
Here is my js:
// validate signup form on keyup and submit
$("#register").validate({
rules: {
......
email: {
required: true,
email: true,
remote: "check_email.php" , async:false
},
},
messages: {
......
email: {required: "Please enter an email address", email: "Please enter a valid email address", remote: "This email is already registered" },
}
}
});
});
And here is my php after the db connection stuff...
$form_email = $_GET['email'];
fb($form_email);
$sql = "SELECT COUNT(*) AS num_rows FROM users WHERE email = " . "'" . $form_email . "'";
fb($sql);
$result = $conn->query($sql);
fb($result->num_rows);
if ($result->num_rows == 0) {
echo 'true';
fb("true");
} else {
echo 'false';
fb("false");
}
The count is always returned as "1", even when I input an email that does not exist.
I've also tried returning
echo json_encode('true');
as I read somewhere that might work, but it did not help. Why is my response always wrong in my php?
The syntax of your remote rule is not correct:
rules: {
......
email: {
required: true,
email: true,
remote: "check_email.php" , async:false
},
}
The way you've written it, the plugin is seeing async as just another rule. Since there is no such "rule" as async, the plugin will choke.
Following the documentation, try this:
rules: {
......
email: {
required: true,
email: true,
remote: "check_email.php"
}
}
or this...
rules: {
......
email: {
required: true,
email: true,
remote: {
url: "check_email.php",
async: false
}
}
}
DEMO: http://jsfiddle.net/KkBSY/
Related
I am using CodeIgniter with jQuery validation. I am using remote to check mobile number and email id is already available or not in the database. So there is no issue when the user registers. I am getting the issue on the edit page.
On the edit page, I just change the name and address but mobile number and email id both are showing already exist. I haven't change mobile and email. I know it will call the controller to check mobile and email are available or not but is there any other way to handle this issue?
I mean, not to check the previous data and check current data if the user enters anything in the field.
I want to check user against the database when creating the account, but NOT check user against the database when editing the account.
$("#edit_member").validate({
errorElement: 'div',
rules: {
name: {
required: true,
alphabets: true,
minlength: 3
},
email: {
required: true,
Email: true,
remote: {
url: baseUrl + "/AddMember/isEmail",
}
},
phone: {
required: true,
number: true,
minlength: 10,
maxlength: 10,
remote: {
url: baseUrl + "/AddMember/isMobile",
// async: false
}
},
address: {
required: true,
minlength: 10
}
},
messages: {
email: {
remote: "Email already Exists"
},
phone: {
remote: "Mobile no already Exists"
},
},
submitHandler: function(form) {//form.submit();}
});
Controller
function isEmail()
{
$email = trim($this->input->get('email'));
$result = $this->addmember_model->isEmail($email);
if($result)
{
echo $msg = "false";
}
else
{
echo $msg = "true";
}
}
function isMobile()
{
$mobile = trim($this->input->get('phone'));
$result = $this->addmember_model->isMobile($mobile);
if($result)
{
echo $msg = "false";
}
else
{
echo $msg = "true";
}
}
Model
function isEmail($email)
{
$result = $this->db->where(['email'=>$email,'is_status'=>1])
->get('members')
->row();
return $result;
}
function isMobile($mobile)
{
$result = $this->db->where(['phone'=>$mobile,'is_status'=>1])
->get('members')
->row();
return $result;
}
Use PHP to determine if the page is Editing or Creating and set a variable as such. You could look at a URL segment with the URI Class.
<?php
$create = ($this->uri->segment(3) == "create") ? TRUE : FALSE;
?>
Then use PHP to write the relevant rule(s) for that particular version of the View.
$("#edit_member").validate({
....
rules: {
....
email: {
required: true,
Email: true,
<?php if ($create) : ?>
remote: {
url: baseUrl + "/AddMember/isEmail",
}
<?php endif; ?>
},
....
The above only works when this part of the JavaScript is in the View file and not included from an external JavaScript file.
Otherwise, if .validate() is part of an externally included JavaScript file, then you can use the .rules() method instead.
After the JavaScript includes (after .validate() invoked), programmatically remove the remote rule.
<?php if ($edit) : ?>
<script>
$(document).ready(function() {
$('[name="email"]').rules('remove', 'remote');
});
</script>
<?php endif; ?>
I have tried to get this to work and have been unsuccessful, I have tried 18 different ways all produced the same result. I have double checked and triple check everything. NOTHING HAS WORKED! I have validation done server side as a fall back if jquery does not work. the validation part works fine its the cheeking if exists that is not working required is working.
My form field
<div class="col-sm-12">
<label>Name</label>
<input type="text" class="form-control" autocomplete="off" name="name" id="name" value="<?php echo isset($_POST['name']) ? $_POST['name'] : '' ?>">
</div>
My jquery vaidate function
$(function() {
$("form[name='register']").validate({
rules: {
name: {
required: true,
name: true,
remote: {
url: "../includes/check.php",
type: "post",
data: {
name: function() {
return $( "#name" ).val();
}
}
}
},
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
}
},
messages: {
name: {
required: "Please enter your name",
minlength: "Name must be at least 4 characters long",
remote: "The name entered is unavailable"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
email: "Please enter a valid email address"
},
submitHandler: function(form) {
form.submit();
}
});
});
My query script
include("db.php");
if(isset($_POST['name'])) {
$name = $_POST['name'];
$db = dbconnect();
$stmt = $db->prepare("SELECT Name FROM users WHERE Name = ?");
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows == 1){
echo 'true';
}else{
echo 'false';
}
}
The problem is not directly related to the remote validation.
You just need to remove
name: true,
from your validation options. This option does not exist in jQuery Validate - there is no validation metod called "name" - and causes a Javascript error when jQuery validate tries to use it:
Cannot read property 'call' of undefined. Exception occurred when checking element name, check the 'name' method.
This means that the "remote" validation never executes because the script crashes before it gets to it.
See https://jsfiddle.net/09djba33/10/ to see the broken functionality - open the Developer Tools and submit the form (with the name field completed), and watch the error message appear in the console.
and https://jsfiddle.net/09djba33/12/ to see the "remote" method working correctly without that spurious option.
P.S. This is why, in the comments, I kept asking you to check what was happening to your ajax request, by looking in the browser tools... :-)
From reading the docs https://jqueryvalidation.org/remote-method/ you can see that while using remote, you need to send data to your server side script because you are using post method. Do it in this way :
remote: {
url: "../includes/check.php",
type: "post"
data: {
username: function () {
return $('#username').val();
}
},
I am trying to avoid adding duplicate email addresses in a MySQL database. Is there any javascript way to check without reload? Like in the Gmail sign-in form?
use validate library : http://docs.jquery.com/Plugins/Validation/Methods/remote
your javascript :
$("#yourFormId").validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: "checkmail.php",
type: "post"
}
}
},
messages: {
email: {
required: "Please Enter Email!",
email: "This is not a valid email!",
remote: "Email already in use!"
}
}
});
checkmail.php :
<?php
$registeredEmails = array('test1#test.com', 'test2#test.com', 'test3#test.com');
$requestedEmail = $_POST['email'];
if( in_array($requestedEmail, $registeredEmails) ){
echo 'false';
}
else{
echo 'true';
}
?>
and you can search in mysql posted email adress instead of $registeredEmails array :)
first off thank you in advance.
I am writing a sign up page in PHP and using Jquery Validate to check the form. It is returning errors when the form is filled out incorrectly, but when it is correctly filled out it is just refreshed and not completing the actions I have delegated in the isset $_POST function. Here is what I am dealing with:
PHP If form is not empty
//Escape high risk symbols
$pw= mysqli_real_escape_string($con, $_POST['pass']);
$username= mysqli_real_escape_string($con, $_POST['pass']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$sex = mysqli_real_escape_string($con, $_POST['sex']);
$signedUp = date("Y-m-d H:i:s");
$hash = password_hash($pw, PASSWORD_DEFAULT);
echo 'Email: '.$email;
echo 'Username: '.$username;
echo 'Sex: '.$sex;
echo 'Signed Up: '.$signedUp;
}
?>
Here is the Form
<form method="post" class="form-signin" id="signup" name="signup">
...
</form>
Here is my validation javascript, it seems that it is not posting
<script src="js/formValidate.js"></script>
<script>
// When the document is ready
$(document).ready(function () {
//validation rules
$("#signup").validate({
onkeyup: false,
onfocusout: false,
errorElement: "div",
errorPlacement: function(error, element) {
error.appendTo("div#errors");
},
rules: {
email: {
required : true,
email: true
//equalTo: "#example3-field2"
},
username: {
required: true,
minlength: 5
},
pass: {
required : true,
minlength: 5
},
cPass: {
required : true,
equalTo : "#pass"
},
sex: {
required : true
},
},
messages: {
email: {
required: "You must enter an email address",
email: "Enter a valid email address"
//equalTo: "Field 1 must be equal to Field 2"
},
username: {
required: "You must choose a username",
minlength: "Username must be a minimum of 5 characters"
},
pass: {
required : "You are required to enter a password!",
minlength : "Password must be at least 5 characters!"
},
cPass : {
required : "You are required confirm your password!",
equalTo : "Passwords do not match"
},
sex : {
required : "You are required to choose a sex"
},
},
submitHandler: function(form) {
form.submit();
}
});
});
</script>
I think the problem is that you're trying to see if the FORM is there (signup), you need to validate one of the fields, for example:
if(isset($_POST['email'])){
Since you seem to be trying to validate the form and that index will never be present in $_POST.
You should use something like that to check if your request is a POST.
if($_SERVER['REQUEST_METHOD'] === 'POST') {
// do your stuff.
}
related questions,
Check whether a request is GET or POST
<script type="text/javascript">
$().ready(function() {
jQuery.validator.addMethod("captcha", function(value, element) {
$.ajax({ url: "verifyCap.php",
type: "GET",
data: "txtCaptcha="+value,
success:
function(msg) {
if(msg == "true")
return true; // already exists
return false;
}
});
},"");
// validate signup form on keyup and submit
$("#signupForm").validate({
rules: {
title: "required",
contactname: "required",
email: {
required: true,
email: true
},
comment: "required",
txtCaptcha:{
required: true,
captcha: true
}
},
messages: {
contactname: "Please enter your contact name",
email: "Please enter a valid email address",
comment: "Please enter your system requierment",
txtCaptcha: {
required:"Please enter verification code",
captcha: "The verification code is incorrect"
}
}
});
});
My verifyCap.php
<?php
session_start ();
if ($_SERVER ["REQUEST_METHOD"] != "GET")
die ( "You can only reach this page by posting from the html form" );
if (($_GET ["txtCaptcha"] == $_SESSION ["security_code"]) && (! empty ( $_GET ["txtCaptcha"] ) && ! empty ( $_SESSION ["security_code"] ))) {
echo "true";
} else {
echo "false";
}
?>
My problem might due to the response format it is not true or false, but i print out whole verifyCap code. Anyone can help?
An ajax request does an get by default instead of a post. Change:
if ($_SERVER ["REQUEST_METHOD"] != "POST")
to
if ($_SERVER ["REQUEST_METHOD"] != "GET")
besides that, do not use $_REQUEST to get your data. Use $_GET instead.
You could also add some settings your ajax request:
type: "POST",
data: "your params here",
You're receiving the whole verifyCap.php code because your PHP isn't interpreted by your web server.
In your verifyCap.php you are using the short tag notation (<? //code ?>).
Not all server uses this php extension, and it is considered deprecated. If your webserver doesn't use this extension, then your code is considered as an XML document, as XML document always start with <? <!-- some XML here --> ?>.
Use <?php //code ?> and your problem should be fixed.
Also, following #XpertEase answer isn't a bad idea either.
Edit: More info on PHP short tags Are PHP short tags acceptable to use? (via #XpertEase)