validate captcha before submit
Solution 1
Assuming the line var session = <?php echo $_SESSION['code'] ?>;
is in your html page.
When the page is generated your captcha image script is not invoked and thus $_SESSION['code']
is not initialized. The value you are getting is the code
from the previous request to captcha_code_file.php
. Once your page is loaded (at-least the html part) and the browser decides to call captcha_code_file.php
your captcha image gets invoked and a new $_SESSION['code']
is created.
I don't recommend this, but if you want to get the current $_SESSION['code']
try to use an Ajax request to retrieve the new $_SESSION['code']
from another php file (don't call captcha_code_file.php
or your session will be reset again.
Note: Never try to validate your captcha at user end. You are defeating the main purpose of captcha.
Solution 2
Create one ajax request for checking capcha using JavaScript, example is provided below:
var postData = $("form").serialize();
var requestUrl = '/check_capcha.php';
$.ajax({
type: "POST",
dataType: "json",
data: postData,
url: requestUrl,
success:function(data){
// success or fail message
}
});
check_capcha.php contains:
if(strcasecmp($_SESSION['code'], $_POST['captcha']) != 0){
//----mismatch values
echo 0;
}else{
echo 1;
}
exit;
Praveen
user1671639 Thanks SO community for helping me with all my queries!! Question I like most: How do JavaScript closures work? Answer I like most: What's the difference between a URI and a URL? People whom I admire most in SO: Jon Skeet, Marc Gravell, David Thomas, T.J. Crowder, dystroy, PSL...
Updated on July 09, 2022Comments
-
Praveen almost 2 years
I've use
captcha
for form registration, within that I have validation engine for form inline validation. I'm stuck in validating the equity ofcaptcha
.<p class="veriText"> <label>Enter the Verification Text </label> <span style="color:red;">*</span> <input class="validate[required] text-input" type="text" name="captcha" id="captcha" class="text" value="" /> </p> <img src="<?= get_bloginfo('template_url'); ?>/captcha_code_file.php?rand=<?php echo rand();?>" id='captchaimg'><br/>
PHP validation: (works perfectly)
if(strcasecmp($_SESSION['code'], $_POST['captcha']) != 0){ //----mismatch values }
But the same thing in js I have tried like
var session = <?php echo $_SESSION['code'] ?>; // this value is different // from captcha image
Is it possible to validate captcha before submitting the form in Javascript/jQuery?