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.

2
  • 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. Commented Jun 4, 2015 at 6: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. Commented Jun 4, 2015 at 7:50

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.