Ajit
Ajit

Reputation: 339

How to use Javascript/jquery code inside a yii controller action?

I want to call a javascript function inside APIController in my yii projects over a repeated interval.

 public function actionMytimer() {
    Yii::app()->clientScript->registerCoreScript('jquery');
    Yii::app()->clientScript->registerCoreScript('jquery.ui');
    $hello = setInterval(test,1000);
    function test(){
        echo 'hellooo interval';
    }  
}

Its very necessary for me to run the "test" method in a particular time interval.Is it possible?if not then any way to do this?. Please help.Thanks in advnc. Here is the current warning message :

Fatal error: Call to undefined function setInterval() in /Library/WebServer/Documents/MediaPult/protected/controllers/APIController.php on line 449

Upvotes: 0

Views: 3101

Answers (2)

Jurijs Kastanovs
Jurijs Kastanovs

Reputation: 685

You can not execute javascript functions from php code just like that. You could try something like:

function actionTest(){
  $cs = Yii::app()->clientScript;
  $cs->registerScript('my_script', 'setInterval(test,1000);', CClientScript::POS_READY);
  $this->render('any_view');
}

Upvotes: 0

Muhammad Ali
Muhammad Ali

Reputation: 732

If you could explain the problem more clearly, It'll be easier for people to provide a good solution.

From what I understand, you want to be able to execute a method on the server side repeatedly. For that, you should output the JavaScript code that does this. It'll be something like this:

<script>
setInterval(function(){
    $.get(<?= Yii::app()->request->baseUrl ?>/actionName");
}, 1000);
</script>

Upvotes: 1

Related Questions