1

I need to reload a content of my Yii widget via AJAX every XX seconds.
This is my widget code:

class UserOnlineWidget extends CWidget
{
  public function init(){

  }

  public function run(){
    $userOnline=User::getOnlineUser();       
    $this->render("userOnLineWidget", array('userOnline'=>$userOnline));
  }

}

And this is the view userOnLineWidget.php:

<div class="userOnline">
<h5>User Online</h5>
<ul>
<?php 
    foreach($userOnline as $user) { 
    ?>
    <li>
        <ul>
            <li><?php echo CHtml::link($user['username'], array('/site/view/'.$user['id'])); ?></li>
            <li><?php echo ($user['online'] != null)? 'online' : 'offline'; ?></li>
        </ul>
    </li>
    <?php 
    }
?>
</ul>
</div>

How can I do this ? I use Yii 1.1.

enfix
  • 6,680
  • 12
  • 55
  • 80
  • Please at least add some code that attempts this. I don't see any sign of Ajax requests. People are not going to do your work for you, but if you show what you have done, someone might point out how to move forward from that point. – crafter Jun 04 '15 at 06:31
  • I have no idea where I need to put Ajax call. I'm new in Yii world so I would to know what's the best practise to do this. I dont' want you do my job. – enfix Jun 04 '15 at 07:50

1 Answers1

2

Here a small example. I hope this help you. Widget which show time from server every second.

//SiteController
public function actionTest()
{
    $this->render('my_view'); //just rendering view
}

public function actionContent()
{
    $this->widget('time'); //return html of widget. use for ajax
}

//my_view.php
<script src="<?php echo  $this->assetsBase ?>/js/jquery-1.10.2.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        setInterval(function() {
            $.get('/site/content', {}, function(data) {
               $('#widget').html(data);
            });
        }, 1000); //update widget content every second
    });
</script>
<div id="widget">
    <?php $this->widget('time'); // render widget  ?>
</div>

//widget
class Time extends CWidget
{
    public function init(){

    }

    public function run(){
        $date = new DateTime();
        $this->render("test", array('time'=>$date->format('H:i:s')));
    }

}

//view for widget test.php
<p><?= $time ?></p>
Danila Ganchar
  • 10,266
  • 13
  • 49
  • 75