Automatically refresh the online user table without refreshing the entire page

I have a table showing a list of online and offline users on my dashboard page. I try to automatically refresh the entire table every 5 seconds to show if there are other users who have just logged in or out without refreshing the whole page. I searched for various topics and pages regarding this, which tells me to use AJAX or JSP. But I can’t make it work.

This is my table:

<div class="col-md-2"> <table class="table table-striped"> <thead> <tr> <th>Status</th> <th>&nbsp;</th> </tr> </thead> <tbody> <?php $online = DB::table('users')->where('group_id', $user->group_id)->orderBy('online', 'desc')->get(); foreach($online as $val=>$key) { ?> <tr> <td><?php if ($key->online == 1) { echo '<span class="label label-success">Online</span>'; } else { echo '<span class="label label-warning">Offline</span>'; } ?></td> <td><?=$key->first_name." ".$key->last_name?></td> </tr> <?php } ?> </tbody> </table> 

I found this code in another thread, but when I tried to use it in my project, it did not load data into my table. I am not very familiar with javascripts or AJAX, so I hope you can help me. It will be very appreciated.

 <script> $(document).ready(function(){ $("#refresh").click(function() { $("#Container").load("content-that-needs-to-refresh.php"); return false; }); }); </script> <div id="Container"> <?php include('content-that-needs-to-refresh.php'); ?> </div> <a href="#" id="refresh">Refresh</a> 
+7
javascript jquery html php
source share
2 answers

In your case, works great for you.

 setInterval(function() { //call ajax here..for your table result } }, 3000); 

and then ajax will give you the result every 3 seconds.

I hope this works for you.

+3
source share

Make sure you download jQuery. You can use the Google CDN or save it and upload it to your own server.

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 

Use setInterval

 <script> $(document).ready(function(){ var refreshUsers = setInterval(function() { $("#Container").load("content-that-needs-to-refresh.php"); }, 5000); // 5000 ms = 5 sec }); </script> <div id="Container"> <?php include('content-that-needs-to-refresh.php'); ?> </div> 

If you want to stop the update, use

 clearInterval(refreshUsers); 
+1
source share

All Articles