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();
}
},
Related
I am using the remote method from the jQuery validation plugin which makes an ajax call. The remote function is activated each time a key is pressed in the input field. I would like to add a delay, so that the ajax request is only trigged when the user stopped pressing a key for some miliseconds.
This problem was posed in 2012 at GitHub but was closed by the developer in 2015:
I'm sorry for the lack of activity on this issue. Instead of leaving
it open any longer, I decided to close old issues without trying to
address them, to longer give the false impression that it will get
addressed eventually.
In the discussion forum, the user lohfu proposed the following solution:
$.validator.methods._remote = $.validator.methods.remote;
var timer = 0;
$.validator.methods.remote = function () {
clearTimeout(timer);
var args = arguments;
timer = setTimeout(function() {
$.validator.methods._remote.apply(this, args);
}.bind(this), 500);
return "pending";
};
However, there are two main problems:
It does not work. If I add the delay and the remote function returns false, then the form gets still submitted.
When I enter something in the input filed which causes an error by the remote function it correctly gets class="error" assigned. If I now select a different input, the class="error" switches to class="valid", although the error message is still present and the error message is still shown. The same happens when I press submit.
Here is a minimal example:
HTML
<form action="test.php" method= "POST" id="form">
Name: <input type="text" name="name"><br>
Email: <input type="email" name="email"><br>
<input type="submit">
</form>
JS
$("#form").validate({
rules: {
name: "required",
email: {
required: true,
email: true,
remote: {
url: "ajax.php",
type: "post"
}
}
},
messages: {
email: {
remote: "Email already exists"
}
}
});
ajax.php
<?php
header('Content-Type: application/json');
$valid = null;
echo json_encode($valid);
This form should never be submitted, because the ajax.php always returns false. However, entering a name and a valid email will submit the form, despite the fact that the error "Email already exists" is shown.
Does the following fiddle work as expected?
You can change the url into true or false instead:
url: '/echo/js/?js=[null|true|false]',
https://jsfiddle.net/ww0zh9jm/2/
..you have to ad the external resources (Fiddle removes them):
https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js
https://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.min.js
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
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/
All,
I've got a form on my page that I use to send emails. On the form page I have the following code:
<input type="text" name="Name" id="your_name" class="contact_form_input_text">
<input type="text" name="Email_Address" id="your_email" class="contact_form_input_text">
<input type="text" name="fill_me_out" id="fill_me_out">
<input type="button" value="Send" id="submit_contact_form_button">
The first text box is a lamecaptcha and I check it on the PHP side to make sure that it wasn't filled out. I also hide it using some JS with this:
jQuery(function(){
jQuery("#fill_me_out").hide();
});
I then have the following form validation before my page submits using jQuery validator:
jQuery("#contact_form").validate({
rules: {
Email_Address: {
required: true,
email: true
},
Name: {
required: true
}
},
messages: {
Email_Address: {
required: "Please enter an email address!",
email: "Please enter a valid email address!"
},
Name: {
required: "Please enter your Name!"
}
}
});
jQuery("#submit_contact_form_button").click(function(event) {
if (jQuery("#contact_form").valid()) {
challengeField = jQuery("input#recaptcha_challenge_field").val();
responseField = jQuery("input#recaptcha_response_field").val();
var html = jQuery.ajax({
type: "POST",
url: site_url + "ajax.recaptcha.php",
data: "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField,
async: false
}).responseText;
if(html == "success")
{
//$("#captchaStatus").html(" ");
// Uncomment the following line in your application
//return true;
jQuery("#contact_form").submit();
}else{
jQuery("#captchaStatus").html("Your captcha is incorrect. Please try again");
Recaptcha.reload();
return false;
}
}
return false;
});
If everything is filled out correctly the page then submits. I have the following check to check the lame captcha:
$lamecaptcha_check = $_POST['fill_me_out'];
if($lamecaptcha_check!=""){
echo '[box style="alert"]Why are you trying to spam us? It could be because you don\'t have Javascript enabled and filled out an incorrect box![/box]';
}else{
//Send the form using mail
}
To submit the form is a button and not a submit so it has to go through the jquery validation to do even be submitted. Somehow I'm still getting blank email messages to come through. Does anyone know anything else I can possibly do to prevent spam/blank email messages? I was thinking I should check the variables on the back end to make sure they are not blank but the form shouldn't even be submitted unless there are some values so I require a valid email address on the initial page. Any ideas are appreciated!
Thanks!
Just because you have a submit button go through jQuery to work, doesn't mean the form can't be submitted otherwise.
A spambot would probably examine the HTML of your form, look at the different fields, and then just send a POST request with the relevant information. It will not evaluate your jQuery.
If you want to do something like this, set the form's action="javascript:;", then update it in your jQuery to the actual value right before submitting.
<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)