Yii: Update content widget with ajax

2.6k Views Asked by At

I have build a notification widget in Yii framework which is called every page and gives the user notifications. Now I would like to update those notifications automatically every 10 seconds with Ajax. The structure is as follows:

<?php

class NotificationsWidget extends CWidget {

public function init(){

}
public function run() {

}

What is the best way to do this? I have searched everywhere, but I cannot seem to find the answer. Maybe I'm just looking with the wrong keywords.. If anyone has another (better) way to do this, please! Only restriction is that it has to be loaded into the interface layout and update at least every 10 seconds.

Thanks a lot:)

1

There are 1 best solutions below

0
On BEST ANSWER

You setup an action in your controller and poll it every 10 seconds, if there is update it will return the notification from a partial view, if there is no update nothing is returned, this is a skeleton implementation to give you an idea, note it will not work as is.

In your layout file

...
// Your normal layout content

<?php Yii::app()->clientScript->registerScript("poll_ajax_notifications",
 'function getNotification(){'.
   CHtml::ajax(array(
       'url'=>array("//notifications/update"),
       'dataType'=>'html',
       'type'=>'GET',
       'update'=>'#divcontainingNotificationWidget',
         )
     ) . '. }
   timer = setTimeout("getNotification()", 10000);
    ', CClientScript::POS_END);

In your Notifications controller

class NotificationsController extends CController {
....
 public function actionUpdate(){
     $user = Yii::app()->user->id;
     // Your logic logic for finding notifications
     if($notificationPresent){ // or any validation to check whether to push data or not
       $this->renderPartial('_notificationWidget',array('widgetData'=>$widgetData)); // pass data required by widget here 
     }
     Yii::app()->end();
  }
 ... 
}

Finally create a partial view in views/notifications folder called _notificationsWidget.php In your view place your widget call

<?php 
  $this->widget('path.to.my.widget',array(
     //widget parameters
   ));