jQuery form validation equalTo hidden field - php

I am working on a form which is validated with jQuery before being submitted. One of the fields is a captcha.
The idea is very simple, the captcha is shown as an image and also stored in a hidden field. When the user enters the captcha in the input field it should be equal to the value of the hidden field. This is the jQuery code I have;
<script>
$(document).ready(function(){
$("#register").validate({
errorElement: 'div', ignore: 'hidden',
rules: {
password: {
required: true
},
password2: {
required: true, equalTo: "#password"
},
agree: {
required: true
},
captcha: {
required: true, equalTo: "#captcha2"
}
},
messages: {
password2: "Please repeat the same password",
captcha: "The captcha you entered is wrong",
agree: "You have to be at least 16 years old and agree to the terms of service"
}
});
});
</script>
The html code for the form is even simpler, but I will show only a part of it.
<p>
<img src='/includes/captcha.php' />
</p>
<p>
<label for="Captcha">Captcha</label>
<em> *</em><input type="text" name="captcha" id="captcha" size="25"
class="require" minlength="5" />
<input type="hidden" name="captcha2" id="captcha2"
value="<?php echo $_SESSION['captcha'];?>" />
This should work. The problem is, however, that I keep getting the error that I set in the jQuery code, "The captcha you entered is wrong".
Can anyone tell me why the code is not working?
BTW, I checked the value of the hidden field and it is the same as the captcha, so that works
UPDATE:
Ok, here is something weird. When I echo the session['captcha'] I get a different value than the value in the hidden field. I get the previous captcha when I echo it. So let's say the captcha value is abc. When I refresh the captcha+hidden field change into def. But when I echo session['captcha'] I still get abc.

Related

jQuery remote validation always returning false

I have the below code for implementing a very basic login system on my site (using jQuery Mobile). The problem is that, when submitting the form through jQuery Mobile (and therefore using the validator), the validator always returns false and throws an error, even if the password is correct. When I wrote a separate form with nothing other than the two textboxes and a submit button and ran it directly to the validation script, it returned the correct value of true or false depending on the given password. What's wrong with the jQuery script that causes it to always return false?
HTML/JS:
<form action="logins.php" method="POST" id="loginForm" name="loginForm" data-ajax="false">
<label for="email" class="ui-hidden-accessible">Email Address:</label>
<input type="text" id="email" name="email" value="" placeholder="Email Address" />
<label for="pass" class="ui-hidden-accessible">Password:</label>
<input type="password" id="pass" name="pass" value="" placeholder="Password" />
<input class="submit" data-role="submit" type="submit" value="Submit" />
</form><br>
<br>
Return to home page
<script>
$('#login').bind('pageinit', function(event) {
$('#loginForm').validate({
onkeyup: false,
onclick: false,
onfocusout: false,
rules: {
email: {
required: true,
email: true
},
pass: {
required: true,
remote: {
url: "passcheck.php",
type: "post"
}
}
},
messages: {
email: {
required: "You must enter an email address.",
email: "You must enter a valid email address."
},
pass: {
required: "You must enter a password.",
remote: "Your username/password combination is incorrect."
}
}
});
});
</script>
PHP (passcheck.php):
<?php
require("common.php");
$query = "SELECT password FROM users WHERE email = :email";
$query_params = array(':email' => $_POST['email']);
try {
$stmt = $conn->prepare($query);
$stmt->execute($query_params);
} catch(PDOException $ex) {
die("Failed to run query.");
}
$hash = $stmt->fetchColumn();
if(crypt($_POST['pass'], $hash) === $hash){
echo "true";
} else {
echo "false";
}
You should be using the submitHandler to write a function to handle the actual checking of the username/password via AJAX using AJAX Form: http://www.malsup.com/jquery/form/#api.
You don't have to use AJAX Form and can write your own method to handle the login checking using the jQuery ajax() method, but AJAX Form has it prewritten for you.
Also, you don't need the onkeyup, onblur, etc. there - all you need is onsubmit set to true. Your code should look like this:
<script>
$('#login').bind('pageinit', function(event) {
$('#loginForm').ajaxForm(); // Set as an AJAX Form - See Documentation Above
$('#loginForm').validate({
onsubmit: true,
rules: {
email: {
required: true,
email: true
},
pass: {
required: true
}
},
messages: {
email: {
required: "You must enter an email address.",
email: "You must enter a valid email address."
},
pass: {
required: "You must enter a password.",
}
},
submitHandler: function(form) {
$("#loginForm").ajaxSubmit();
}
});
});
</script>

Popping an alert when Getting Information

How can i display an alert message or alert box when getting the information(not submitting)
i have few form structures(text type) in my html when i enter the id in one of the form and press get button all the other forms will be filled based on the form submitted.
for the above i am using json and jquery
Ex:
Jquery
$(document).ready(function(){
$("#button1").click(function(){
$.post('script_1.php', { id: $('input[name="id"]', '#myForm').val() },
function(json) {
$("input[name='title']").val(json.title);
$("input[name='name']").val(json.name);
$("input[name='age']").val(json.age);
$("#institution").val(json.institution);
}, "json");
});
json:
$abc_output = array('title' => $row['title'],'name' => $row['name'],'age' => $row['age'], 'institution' => $row['institution']);
echo json_encode($abc_output);
now the problem is all the id's will not be having information so when the user enters some id with no information pop up or alert box need to be submitted saying no id.
How can i do that?
Note: as it is get info the result will be displayed on the same page, if its submit i could have echoed id not found in DB in the server side php(script_1.php) which is not the case here.
Html:
id: <input type="text" name="id"/>
<div id="hidden" style="display: none;">
<p>Title:<input type="text" name="title"/></p>
<p>name:<input type="text" name="rno"/></p>
<p>age:<input type="text" name="age"/></p>
Institution: <select id="institution" name="institution">
<option value="None">-- Select --</option>
<option value="ab">ab</option>
<option value="bc">bc</option>
</select>
</div>
<br/>
<input type="button" id="button1" value ="Get Info" onclick="document.getElementById('hidden').style.display = '';"/>
</form>
<div id="age"></div>
</body>
</html>
It may be helpful to set up an AJAX error handler, to handle things like session timeouts, json 'parseerror', etc.
$(document).ajaxError(function() {
alert( "Triggered ajaxError handler." );
});
This can help you to determine if the problem is with the success callback not being called.
You didn't post your opening <form> tag, but i'm assuming it has an id of 'myForm' (which you won't need).
I checked your javascript, and found a syntax error (a missing });). Try this:
$(document).ready(function(){
$("#button1").click(function(){
$.post('script_1.php', { id: $('input[name="id"]').val() }, function(json) {
$("input[name='title']").val(json.title);
$("input[name='name']").val(json.name);
$("input[name='age']").val(json.age);
$("#institution").val(json.institution);
}, "json");
});
});
Notice I removed #myForm from the part that passes the values to php. The form itself does not have a value, the individual fields do.

Why is my JS code running in an apparent loop?

I have the following code:
JS
<script type="text/javascript">
$(function(){
$('#fgotpwfield').hide();
$('#login_submit').click(function() {
$('#form_result').fadeOut('fast');
$('#myccrxlogin input').removeAttr('disabled');
$('#myccrxlogin').submit();
});
if ($("#myccrxlogin").length > 0) {
$("#myccrxlogin").validate({
rules: {
email: { required: true, email: true },
password: 'required'
},
messages: {
email: { required: 'Your email address is required.',
email: 'Please enter a valid email address.'},
password: 'Your password is required.'
},
submitHandler: function(form) {
$('#myccrxlogin input').attr('disabled','true');
$('#login_submit').fadeOut('fast');
$('#forgotpw').fadeOut('fast');
$('body').append('<div id="page_load"></div>');
var email = $("#email").val();
var pw = $("#password").val();
var data = 'email=' + email + '&password=' + pw;
$.ajax({
url: "hidden url",
type: "POST",
data: data,
cache: false,
success: function (html) {
$('#page_load').remove();
if(html == 'OK') {
alert(html);
} else {
//$("#password").val('');
$("#form_result").html(html);
$('#form_result').fadeIn('slow');
$('#myccrxlogin input').removeAttr('disabled');
$('#login_submit').fadeIn('slow');
$('#forgotpw').fadeIn('slow');
}
}
});
} /*close submit handler */
});
};
});
</script>
HTML
<div id="form_result" style="margin:10px; display:none;" class="field-submit-error"></div><div style="clear:both;"></div>
<div id="loginformfield">
<p style="font-size:24px; font-weight:bold; font-family:Arial, Helvetica, sans-serif; color:#f93;">Login</p>
<form class="loginform" id="myccrxlogin" method="post" target="_parent">
<p>
<input name="email" type="text" id="email" tabindex="1" />
<label for="email">E-mail</label></p>
<p><input name="password" type="password" class="text large required" id="password" tabindex="2" />
<label for="password">Password</label></p>
<div class="loading"></div>
<p>I forgot my password</p>
<p><a class="readmore" href="#" id="login_submit" style="margin-bottom:0.5em;" tabindex="3">Login!</a></p>
</form>
</div>
A person enters their email and password, the file is first validated then run through an ajax call successfully. The ajax PHP page echo's either an error or 'OK'. I know the code gets to 'OK' because the alert(html) is triggered but it runs infinitely. Not sure why?
update
I believe I might be running into the recursion issue described here: http://docs.jquery.com/Plugins/Validation#General_Guidelines although I am not sure it applies.
I can't step through, but I believe you need to have your submithandler return false.
I believe the form is being submitted by the form action and the ajax submission.
Looking at the recursion link you posted, you would need to change this line:
$('#myccrxlogin').submit();
so that the raw form is being submitted, rather than the jquery-ized version of the form. In their example,
$(form).submit();
becomes
form.submit();
Try changing your submit line in a similar way.
The amazingly unclear and wild answer is this: I had to add the following into my ajaxed-PHP page. Something about running locally or with the setup I have is wacky. Hopefully this helps somebody.
Add to the first line of your ajax php page:
header('Access-Control-Allow-Origin: *');

jquery recaptcha php

I don't know how can i validate the recaptcha thing via jQuery. Please help. I have the contact us form with the following fields:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.validate.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#signup').validate({
rules: {
name: {
required: true
},
email: {
required: true,
email: true
},
messages: {
name: {
required: 'FULL NAME Missing'
},
email: {
required: "E-MAIL ADDRESS Missing",
email: "E-MAIL ADDRESS Not Valid"
}
});
});
</script>
<form action="index.php" method="post" name="signup" id="signup">
<p>
Full Name
<br>
<input name="name" type="text" class="required" id="name" title="Type your Full Name into this box" value="<?php echo $_POST['name']; ?>">
</p>
<p>
E-Mail Address
<br>
<input name="email" type="text" id="email" title="Type your E-Mail Address into this box" value="<?php echo $_POST['email']; ?>">
</form>
Validation with the jQuery is working, but no idea how to implement the recaptcha into this.
thanks all for your comments,will get it done by simple library :)
http://www.white-hat-web-design.co.uk/articles/php-captcha.php
And validation by using php after submitting of the form (it was easy for me to implement in less time in php than jquery. :) .
special thanks to Felix Kling :).
Dave
For those sort of validate, there is a validation method in jQuery validate plugin known as remote.
Check it here
$("#myform").validate({
rules: {
email: {
required: true,
email: true,
remote: "check-email.php"
}
}
});
In this check-email.php should return string "true" to be considered valid. and string "false" to be considered false.

Validate AJAX generated form field

I have a form with select Field A. This field can be dynamically populated based on the URL or it can be selected as usual.
Once a value has been selected in Field A either way, select Field B is populated and exposed with JQuery AJAX.
Here is the problem. If Field A is left untouched, and is dynamically populated by the URL, Field B will properly validate. However, if Field A is changed, Field B will no longer attempt to validate.
Field A
<select name="FieldA" id="FieldA">
<option value="">Please Select</option>
<?php
while($FieldA= mysql_fetch_array($result2)) {
?>
<option value="<?php echo $FieldA['FieldAID']; ?>"<?php if ($var == $FieldA['FieldAID']) echo " selected=\"selected\""; ?>><?php echo $FieldA['FieldAName']; ?> </option>
<?php } ?>
</select>
Field B
<select name="FieldB" id="FieldB">
<option value="">Please Select</option>
<?php
while($FieldB = mysql_fetch_array($result)) {
?>
<option value="<?php echo $FieldB['FieldBID']; ?>"><?php echo str_replace('|',' - ',$FieldB['FieldBName']); ?></option>
<?php } ?>
</select>
Validation Criteria
<script language="JavaScript" type="text/javascript">
var frmvalidator = new Validator("FormName");
frmvalidator.addValidation("FieldA","req","Please select FieldA.");
frmvalidator.addValidation("FieldB","req","Please select FieldB.");
</script>
Everything works EXCEPT that the AJAX call breaks the validation for Field B. If Field B is not repopulated, it works fine. Field B is constructed with an include file so it is the same whether populated by the page or the AJAX call.
Thank you!
I suppose you are using this js library:
http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
If it gives you many problems, perhaps it's time to change to a more powerful validation library.
I recommend this:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
Which appears in jquery webpage, and it is very complete. The syntax is more or less like this:
$("#signupForm").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
},
email: {
required: true,
email: true
},
topic: {
required: "#newsletter:checked",
minlength: 2
},
agree: "required"
},
messages: {
firstname: "Please enter your firstname",
lastname: "Please enter your lastname",
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
confirm_password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long",
equalTo: "Please enter the same password as above"
},
email: "Please enter a valid email address",
agree: "Please accept our policy"
}
});

Categories