简体   繁体   中英

Call A Helper Function to a function in Javascript with Time Interval

Does someone here know how to echo a function from a helper and call it every some time interval? I want to use it so I don't have to call my function in my every controller.

I have these 2 functions in my helper:

function online_count() {
  $CI =& get_instance();
  $CI->load->model('Auth_model');
  return $CI->Auth_model->online_count();  
}

function online_members() {
 $CI =& get_instance();
 $CI->load->model('Auth_model');
 return $CI->Auth_model->online_members(); 
} 

Here's a code snippet for my view which needs those functions:

<ul class="nav nav-pills pull-right">
 <li class="dropdown">
  <a href="javascript:void(0)" data-toggle="dropdown" class="dropdown-toggle">Online </b> <span class="badge badge-success"><?php echo online_count(); ?></span></a>
 <?php
   if(online_count() != 0) { ?>
   <ul class="dropdown-menu">
 <?php
  $members = online_members(); 
      foreach($members as $members_data) { ?>
   <li><a href="javascript:void(0)" onclick="javascript:chatWith('<?=$members_data->username;?>')"><?php echo $members_data->firstname; ?></a></li>
 <?php }
 ?>
 </ul>  
 <?php  }
 ?>
</ul>   

And here's my script:

<script>
 function online() {
  //Calls the function
 }

 setInterval(online, 5000);
</script>

Hope someone could help. Thanks!

try like this

 <script>    
     setInterval(function(){
      <?php online_members(); ?>
     <?php online_count(); ?>

     },5000);
    </script>

I made this:

$(document).ready(function(){

 setInterval(function(){
 $.ajax({
 url: "/system/online",
 type: 'post',
 data: {"token": " "}, 
 success: function(html){
  $("#online").html(html);
 }
});
}, 1000);

setInterval(function(){
$.ajax({
url: "/system/online_members",
type: 'post',
data: {"token": " "}, 
success: function(html){
 $("#online_members").html(html);
  }
 });
}, 1000);  
});

But I'll improve this for shorter lines of code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM