2

I am generating a checkbox using the corresponding method of CHtml, and I want to run some JavaScript code before and after the AJAX request. Here is the code:

echo CHtml::checkBox('markComplete', FALSE, 
    array(
        'class' => 'markComplete',
        'ajax'  => array(
            'type'       => 'POST',
            'url'        => $this->createUrl('/events/events/MarkComplete'),
            'data'       => 'event_status='.$events['id'],
            'beforeSend' => 'function(){ $(this).parent("TR").hide(); }',
            'success'    => 'function(resp) { $("#right").append(resp); }'
        ),
    )
); 

How can I tell Yii that beforeSend and success are JavaScript code and not plain strings?

1 Answer 1

4

Better option available starting from Yii 1.1.11

All framework classes now support custom JavaScript snippets through CJavaScriptExpression. Use it like this:

'ajax' => array(
    'beforeSend' => new CJavaScriptExpression(
        'function(){ $(this).parent("TR").hide(); }'
    ),
    // ...
)

The option of prefixing strings with js: is still available by default, but it can now be disabled as required using an optional parameter on CJavaScript::encode.

Original answer

If you want to include literal JavaScript code as part of options, the convention in Yii is to prefix the code with js:. So you would write it like this:

'ajax' => array(
    'type'=>'POST',
    'url'=>$this->createUrl('/events/events/MarkComplete'),
    'data'=>'event_status='.$events['id'],
    'beforeSend' => 'js:function(){            
        $(this).parent("TR").hide();

    }',
    'success'=>'js:function(resp) {
        $("#right").append(resp);

    }'
    ),
)

Unfortunately this is not well documented, which is why people run into exactly this problem every now and then.

Sign up to request clarification or add additional context in comments.

3 Comments

if console.log it... it show error on firebug console. ** elem.nodeName is undefined [Break On This Error] ...ks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.typ... jquery.js (line 2317)**
when i print $(this) in console it returns me ajax object
@AlizainPrasla: That means that your code needs debugging, not that putting js: in front isn't what you should do. So go ahead and debug it; unfortunately I can't help with that.

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.