How to update captcha image on update / upload page?

I want my site to update the captcha image every time it loads, so I have a javascript method called by the onload () event. Here I have the following line:

document.getElementById('yw0_button').click;

Firebug does not detect any errors, and for testing purposes, I added a warning immediately after the displayed line, and a warning appears every time the page loads. However, the image is not updated!

Here is what I find relevant in the view file:

<?php if(extension_loaded('gd')): ?>
    <div class="row">
        <?php echo $form->labelEx($model,'verifyCode'); ?>
        <div>
            <?php
            $this->widget('CCaptcha',
                          array('showRefreshButton'=>true,
                                'buttonType'=>'button',
                                'buttonOptions'=>
                                                    array('type'=>'image',
                                                          'src'=>"/path/images/refresh-icon.png",
                                                          'width'=>30,
                                                    ),                                                            
                                'buttonLabel'=>'Refrescar imagen'),
                          false); 
            ?>
            <br>
            <?php echo $form->textField($model,'verifyCode'); ?>
        </div>
    <div class="hint">
        Porfavor ingrese las letras como las ve en la imagen superior.
        <br/>No hay distincion entre minúsculas y mayúsculas.</div>
    </div>
<?php endif; ?>

Any ideas?


@k to z just saw this! Yes, of course, if you could help me find a better solution, that would be awesome! This is what I find relevant in the view file:

<?php if(extension_loaded('gd')): ?>
        <div class="row">
            <?php echo $form->labelEx($model,'verifyCode'); ?>
            <div>
                <?php
                $this->widget('CCaptcha',
                              array('showRefreshButton'=>true,
                                    'buttonType'=>'button',
                                    'buttonOptions'=>
                                                        array('type'=>'image',
                                                              'src'=>"/path/images/refresh-icon.png",
                                                              'width'=>30,
                                                        ),                                                            
                                    'buttonLabel'=>'Refrescar imagen'),
                              false); 
                ?>
                <br>
                <?php echo $form->textField($model,'verifyCode'); ?>
            </div>
        <div class="hint">
            Porfavor ingrese las letras como las ve en la imagen superior.
            <br/>No hay distincion entre minúsculas y mayúsculas.</div>
        </div>
    <?php endif; ?>

accessRules() captcha, thats about all. - , ?

+5
8

, - , Yii.. CAPTCHA, : , onload, :

$( '# yw0_button') ();.

, , ! , , , captcha , . !

: , , onload html-,

<body onload="initialize()"> 
.. 
</body> 

js:

function initialize() 
{ 
     $('#yw0_button').click(); 
} 
+6

, , Soph. , , JavaScript. , , , .

- , , , . , , POST (GET request). , Soph , - , POST , .

Yii captcha. , system.web.widgets.captcha. CCaptcha CWidget, , - :

<?php 
    $this->widget("CCaptcha", array(
    'buttonLabel' => "Generate another code",
    'showRefreshButton' => false,
    'clickableImage' => true
));
?>

CCaptchaAction, , , . , Yii -, Captcha CaptchaAction, CCaptcha CCaptchaAction components - .

.

run() CCaptchaAction , , if - , render_refreshed GET .

Captcha refresh - false, CCaptcha one. renderImage, , HTML- . , captcha, src img. refresh true render_refreshed.

CaptchaAction.php:

<?php

Yii::import("system.web.widgets.captcha.CCaptchaAction");

class CaptchaAction extends CCaptchaAction
{
    const RENDER_REFRESHED_GET_VAR = "render_refreshed";

    public function run()
    {
        if (isset($_GET[self::REFRESH_GET_VAR]))  // AJAX request for regenerating code
        {
            $code = $this->getVerifyCode(true);
            echo CJSON::encode(array(
                'hash1' => $this->generateValidationHash($code),
                'hash2' => $this->generateValidationHash(strtolower($code)),
                // we add a random 'v' parameter so that FireFox can refresh the image
                // when src attribute of image tag is changed
                'url'=> $this->getController()->createUrl($this->getId(), array(
                    'v' => uniqid()
                )),
            ));
        }
        else if (isset($_GET[self::RENDER_REFRESHED_GET_VAR]))
        {
            $this->renderImage($this->getVerifyCode(true));
        }
        else
            $this->renderImage($this->getVerifyCode());
        Yii::app()->end();
    }
}

Captcha.php:

<?php

Yii::import("web.system.widgets.CCaptcha");

class Captcha extends CCaptcha
{
    public $refresh = false;

    protected function renderImage()
    {
        if (!isset($this->imageOptions['id']))
            $this->imageOptions['id'] = $this->getId();

        if ($this->refresh)
        {
            $url = $this->getController()->createUrl($this->captchaAction, array(
                'v' => uniqid(),
                CaptchaAction::RENDER_REFRESHED_GET_VAR => 1
            ));
        }
        else
        {
            $url = $this->getController()->createUrl($this->captchaAction, array(
                'v' => uniqid()
            ));
        }
        $alt = isset($this->imageOptions['alt']) ? $this->imageOptions['alt'] : '';
        echo CHtml::image($url, $alt, $this->imageOptions);
    }
}

, . , , :

...

// Creating order model instance
$model = new MyModel();
$refreshCaptcha = true;

if (isset($_POST['MyModel']))
{
    $refreshCaptcha = false;
    ...
}

...

$this->render("myView", array(
    'model' => $model,
    'refreshCaptcha' => $refreshCaptcha
));

captcha myView :

<?php 
    $this->widget("Captcha", array(
    'buttonLabel' => "Generate another code",
    'showRefreshButton' => false,
    'clickableImage' => true,
    'refresh' => $refreshCaptcha
));

actions , CCaptchaAction CaptchaAction:

public function actions()
{
    return array(
        'captcha'=>array(
            'class'=>'CaptchaAction',
            'backColor'=>0xFFFFFF
        )
    );
}

, , . , -.

+5

- Ezze:

clientValidation, :

class CaptchaValidatorRefresh extends CCaptchaValidator
{
    public function clientValidateAttribute($object,$attribute)
{
    $js="";

    if(!$this->allowEmpty)
    {
        $message=$this->message!==null ? $this->message : Yii::t('yii','The verification code is incorrect.');

        $js="
            if($.trim(value)=='') {
                messages.push(".CJSON::encode($message).");
            }
        ";
    }       
    return $js;
    }
}

public function rules()
{
    return array(
        array('verifyCode', 'CaptchaValidatorRefresh', 'on'=>'request', 'allowEmpty'=>!CCaptcha::checkRequirements()),                          
    );
}
+1

javascript:

jQuery(document).ready(function() {
    jQuery.ajax({
        'success':function(html){jQuery("#yw0").attr("src",html)},
        'url':'/checkout/finish/captcha?refresh=1',
        'cache':false
    });
    return false;
});
+1

(?) ():

Yii::app()->getController()->createAction('captcha')->getVerifyCode(true);
+1

: http://www.yiiframework.com/extension/captcha-extended/

and change CaptchaExtendedAction.php (path: extensions / captchaExtended)

on line 154

$this->renderImage($this->getVerifyCode());  

to

$this->renderImage($this->getVerifyCode(true));
+1
source

You can write a script before the beginWedget form.

on each page load generates a new captcha code.

  $script=' $(document).ready(function() {

            document.getElementById("yw0_button").click();
    });';
  Yii::app()->clientScript->registerScript('yw0_button', $script);

  $form=$this->beginWidget('CActiveForm', array(
    'id'=>'test-form',
    'action'=>Yii::app()->createUrl('controllerName/actionName'),
    'enableClientValidation'=>true, 
    'clientOptions'=>array(
        'validateOnSubmit'=>true,
    ),
  ));

he works for me.

I hope this also works for you.

0
source

I have a better solution for you guys:

public function beforeAction($action)
{
    if($action->id == 'captcha'){
        $action->getVerifyCode(true);
    }
    return parent::beforeAction($action); 
}

Put these codes in the controller that you turn on the captcha action!

0
source

All Articles