0

I want to have a reload button beside my captcha image to reload it with jquery in codeigniter. I searched the net to find a solution for it, but all I found confused me.

this is my controller:

function create_captcha()
{                                
    $expiration = time()-300; // Two hour limit
    $this->db->query("DELETE FROM captcha WHERE captcha_time < ".$expiration);
    $vals = array(
                //'word'         => 'Random word',
                'word_length' => 4,
                'img_path' => './uploads/captcha/',
                'img_url' => base_url().'uploads/captcha/',
                'font_path' => './system/fonts/texb.ttf',
                'img_width' => '110',
                'img_height' => '30',
                'expiration' => '3600'
            );

    $cap = create_captcha($vals);

    //puts in the db
    $captchadata = array(
                'captcha_id'    => '',
                'captcha_time'  => $cap['time'],
                'ip_address'    => $this->input->ip_address(),
                'word'          => $cap['word']
            );

    $query = $this->db->insert_string('captcha', $captchadata);
    $this->db->query($query);

    if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') echo $cap['image'];
    else return $cap['image'];

and this is my view:

<div class="captcha-area">
    <? echo form_input('captcha', '', 'class="field text captcha"')?>
    <div id="cap-img">
        <? echo $image;?>
    </div>
    <a title="reload" class="reload-captcha" href="#"><img src="<? echo base_url(); ?>images/reload.png" /></a>                                
    <div class="clear"></div>
 </div>
 <script>
      $(function(){
          var base_url = '<?php echo base_url(); ?>';
          $('.reload-captcha').click(function(event){
              event.preventDefault();
              $('.captcha-img').attr('src', base_url+'dashboard/create_captcha?'+Math.random());
          });
       });
 </script>

EDIT:

this is the source code after loading the site

<div class="captcha-area">
   <input type="text" name="captcha" value="" class="field text captcha">
   <div id="cap-img">
       <img src="http://example.com/uploads/captcha/1382346264.1026.jpg" width="110" height="30" class="captcha-img" style="border:0;" alt=" ">
   </div>
   <a title="reload" class="reload-captcha" href="#"><img src="http://example.com/images/reload.png"></a>                                
   <div class="clear"></div>
</div>

and when I click on the reload button it changes the src attribute to something like:

<img src="http://example.com/dashboard/create_captcha?0.8049291325733066" width="110" height="30" class="captcha-img" style="border:0;" alt=" ">

3 Answers 3

2

Append your controller name and use ajax like,

$(function(){
    var base_url = '<?php echo base_url(); ?>';
    $('.reload-captcha').click(function(event){
        event.preventDefault();
        $.ajax({
           url:base_url+'dashboard/create_captcha?'+Math.random(),
           success:function(data){
              $('.captcha-img').attr('src', data);
           }
        });            
    });
});
Sign up to request clarification or add additional context in comments.

4 Comments

of course I had the controller but I omitted it here. I edited the post, have a look at it.
@Afshin see I've changed my answer you need to use ajax for that
this time it put whole html code in src attribute. it seems like: src="<html>....</html>"
I changed your code a little bit, and posted it below. thank you very much for your help
2

#You may reload img by using ajax and javascript see my code

#You must create a folder captcha in your CI root folder

#The folder captcha permission to 777 or 666 mean(read, write for all)

#Then look like ci/captcha

#Then look like ci/application

My html.php view

<html>
<head>
<script>
    function postRequest(strURL) 
    {
        var xmlHttp;
        if (window.XMLHttpRequest) // Mozilla, Safari, ...
        { 
            var xmlHttp = new XMLHttpRequest();
        } 
        else if (window.ActiveXObject) // IE 
        { 
             var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        else
        {
            alert("your browser does not support AJAX");
            return;
        }
        xmlHttp.open('POST', strURL, true);

        xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        xmlHttp.onreadystatechange = function() 
        {
            
            if (xmlHttp.readyState == 4 && xmlHttp.status==200) 
            {
                reload_captcha(xmlHttp.responseText);
            }
        }
        xmlHttp.send(strURL);
    }
    
    function reload_captcha(str)
    {
        document.getElementById("captcha-img").innerHTML = str;
    }
    
    function get_captcha()
    {
        //<a href="#" onclick="JavaScript:get_captcha()" ></a>
        document.getElementById("captcha-img").innerHTML = '<img src="<?php echo base_url('asset/img/loader.gif'); ?>" height="35" width="37" />';
        var url="<?php echo base_url('index/reload_captcha'); ?>";
        postRequest(url);
    }
</script>
</head>
<body>
<label>Human test</label>
<input type="text" autocomplete="off" maxlength="5" name="captcha" value="" />
<span id="captcha-img" class="captcha-img">
    <?php echo $captcha_img; ?>
</span>
<a href="#reload" onclick="JavaScript:get_captcha()" ><img class="reload-img" src="<?php echo base_url('asset/img/reload.png'); ?>" alt="reload" /></a>
</body>
</html>

My index.php Controller

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Index extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->library('form_validation');
        $this->load->helper('date');
    }
    public function index()
    {
        $this->form_validation->set_rules('captcha', 'Security','trim|required|xss_clean|callback_check_captcha');
        
        if($this->form_validation->run() == False)
        {
            $data['captcha_img'] = $this->get_captcha();
        
        $this->load->view('html',$data);
    }
}

private function _generate_string($min, $max)
{
    $pool = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    $pool = str_shuffle($pool);
    $str = '';
    
    for ($i = 0; $i < 5; $i++)
    {
        $str .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
    }
    
    return $str;
}
    
public function get_captcha()
{
    $this->load->helper('captcha');
    
    $word = $this->_generate_string(2,5);
    
    $vals = array(
                    'word' => $word,
        'img_path'   => './captcha/',
        'img_url'    => base_url().'captcha/',
        'img_width'  => 120,
        'img_height' => 35,
        'border' => 0, 
        'font_path' => './system/fonts/texb.ttf',
        'expiration' => 3600 //1 houre
    );
    
    $cap = create_captcha($vals);
    
    $this->session->set_userdata($cap['word']);
        
    return $cap['image'];
}

public function reload_captcha()
{
    $new_captcha = $this->get_captcha();
    echo "".$new_captcha;
}

public function check_cap_tcha()
{
    $session_captcha_code = $this->session->userdata('word');
        
    if($session_captcha_code == $user_captcha_code)
    {
        return true;
    }else{
        $this->form_validation->set_message('check_captcha', "Security code does not match !");
        return false;
    }
}
}

And after all it's work well !

Comments

-1

I changed Ruhan Kumar's code a little bit and could get the satisfying code:

<script>
     $(function(){
         var base_url = '<?php echo base_url(); ?>';
         $('.reload-captcha').click(function(event){
             event.preventDefault();
             $.ajax({
                 url:base_url+'admin/dashboard/create_captcha',
                 success:function(data){
                     $('.captcha-img').replaceWith(data);
                 }
             });            
          });
      });
</script> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.