I have a captcha form using codeigniter. i am reload the captcha image using ajax.But problem is when i enter the correct code it didn't work properly. It shows my given words are wrong. plz help
Here is my controller:
function create_captcha(){
$this->load->helper('captcha');
$config = array('img_path' => './assets/captcha/',
'img_url' => base_url().'assets/captcha/',
'img_width' => '140',
'img_height' => '35',
'font_path' => './assets/fonts/OpenSans-ExtraBold.ttf',
'expiration' => 7200);
$captcha = create_captcha($config);
$image = $captcha['image'];
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo $image;
}
else {
return $image;
}
$this->session->set_userdata('captchaword', $captcha['word']);
}
function check_captcha(){
$captcha_code = $this->input->post('captcha');
if ($captcha_code == $this->session->userdata('captchaword')) {
return TRUE;
}
else {
$this->form_validation->set_message('check_captcha', 'Wrong Captcha Code!');
return FALSE;
}
}
function seabooking()
{
$this->form_validation->set_rules('captcha', 'Captcha', 'trim|required|callback_check_captcha|xss_clean');
if ($this->form_validation->run() == FALSE) { //code} else { echo 'ok';}
}
Here is my view:
<label for="captcha" class="col-sm-3 control-label custom-label">Enter the Captcha</label>
<div class="col-sm-2 image" id="cap_div">
<?php echo $image;?>
</div>
<?php print_r($this->session->userdata('captchaword')); ?>
<a href="#" id="reload" class="clickedimage">Reload Image</a>
<div class="col-sm-4">
<input type="text" class="form-control" name="captcha" id="captcha" placeholder="Type captcha word" />
<?php echo form_error('captcha');?>
</div>
Here is ajax call code:
<script type="text/javascript">
$(document).ready(function(){
$('.clickedimage').click(function(){
grabImage();
return false;
})
function grabImage()
{
$.ajax({
url: '<?php echo base_url('node/captcha_ajax');?>',
cache: false,
success: function(imagefromthecontroller) {
var newCaptcha = $('<div class="col-sm-2" id="cap_div">'+imagefromthecontroller+'</div>');
$('#cap_div').replaceWith(newCaptcha);
}
});
}
});
</script>
</body>
When you reload the captcha, you're not saving the captcha's new contents.
$this->session->set_userdata('captchaword', $captcha['word']);
This line of code above needs appear before you return $image
.
I'd also review this line of code:
(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
This conditional appears taken and modified from this question. As it exists in your question, this condition will always be true when $_SERVER['HTTP_X_REQUESTED_WITH']
is not empty because "xmlhttprequest"
will always evaluate as true.