Shark Shark - 1 year ago 151
Ajax Question

Yii: Update content widget with ajax

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:


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:)

Answer Source

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(){'.
     ) . '. }
   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 

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

     //widget parameters
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download