Reputation: 113
i have a jQuery and php captcha after i add the code to validate the match its not working
here is my jQuery code
$(document).ready(function() {
$('img#captcha-refresh').click(function() {
change_captcha();
});
function change_captcha(){
document.getElementById('captcha').src="reCaptcha/get_captcha.php?rnd=" + Math.random();
}
var captchascr = $('#captcha').attr('src');
$('#captcha-code').on('change', function(){
var captchaval = $(this).val();
if (captchascr == captchaval) {
console.log('match');
}else {
console.log('No match');
}
});
});
html
<div class="captcha-box">
<img src="reCaptcha/get_captcha.php" id="captcha" />
</div>
<div class="text-box">
<label>Type the two words:</label>
<input name="captcha-code" type="text" id="captcha-code">
</div>
<div class="captcha-action">
<img src="reCaptcha/refresh.jpg" id="captcha-refresh" />
</div>
here is the php code
session_start();
$word_1 = '';
for ($i = 0; $i < 4; $i++)
{
$word_1 .= chr(rand(97, 122));
}
for ($i = 0; $i < 4; $i++)
{
$word_2 .= chr(rand(97, 122));
}
$_SESSION['random_number'] = $word_1.' '.$word_2;
$dir = 'fonts/';
$image = imagecreatetruecolor(165, 50);
$font = "recaptchaFont.ttf"; // font style
$color = imagecolorallocate($image, 0, 0, 0);// color
$white = imagecolorallocate($image, 255, 255, 255); // background color white
imagefilledrectangle($image, 0,0, 709, 99, $white);
imagettftext ($image, 22, 0, 5, 30, $color, $dir.$font, $_SESSION['random_number']);
header("Content-type: image/png");
imagepng($image)
here is the session is created at the php file i just don't know how to call the session so i make the matching, can someone please help?
Upvotes: 2
Views: 1549
Reputation: 1405
Make the AJAX
Call to the new file named validate_captcha.php
.
The PHP Code in file to handle AJAX Call
<?php
session_start();
$task = !empty($_POST['task']) ? $_POST['task'] : null;
$response = 'false';
if ( $task == 'validateCaptha' ){
$inputCaptcha = !empty($_POST['inputCaptcha']) ? $_POST['inputCaptcha'] : null;
$sessionCaptcha = $_SESSION['random_number'];
if ($inputCaptcha == $sessionCaptcha){
$response = 'true';
}else{
$response = 'false';
}
echo $response;
exit();
}
?>
The jQuery AJAX Code
$(document).ready(function() {
$('img#captcha-refresh').click(function() {
change_captcha();
});
function change_captcha(){
document.getElementById('captcha').src="reCaptcha/get_captcha.php?rnd=" + Math.random();
}
$('#captcha-code').on('change', function(){
var inputCaptcha = $(this).val();
$.ajax({
url: 'reCaptcha/validate_captcha.php',
type: 'POST',
async: false,
data: {'task':'validateCaptha', 'inputCaptcha':inputCaptcha},
success: function(response){
if (response=='true'){
alert('Match');
}else{
alert('Not Match');
}
}
});
});
});
Hope this may help you.
Upvotes: 1