Call a javascript function from a controller?

Hi YiiMaster,

Do you know how to call a javascript function from a controller?(I know how to call javascript from view)

Here is my javascript function. I need to call this function after certain logic.

Do I need to create a component which contain this javascript and render the view in my controller?

<script type="text/javascript">

alert("You pressed OK!");

</script>

I think you should be doing that in your view, but you can use ClientScript::register…

Thanks jayrulez.

ClientScript::register is register the whole javascript file into view,right?

But how to call the alert function?




function actionTest(){

  $cs = Yii::app()->clientScript;

  $cs->registerScript('my_script', 'alert("Hi there!");', CClientScript::POS_READY);

  $this->render('any_view');

}



Thanks samdark,

Will the alert function get triggered if I’m not render the view? (I test the alert in my code but I didn’t get the alert.)

What I want is just calling a javascript function.

You must realize javascript is executed on the client-side. You can’t just execute it on the server-side. Means the javascript must be send to the client as part of the actual html output. registerScript() does exactly that, it injects your javascript into the actual html output.

If you don’t need to render anything but you need some kind of feedback-system (eg “you clicked ok” etc), then you may use ajax. There are several threads about it in this forum.