简体   繁体   中英

Display Online users in a chat application

I have a chat application and in this application, i want to show online users in a chatroom. I have a database that records online users and it keeps changing whenever a new user comes. Whenever a users leaves, it is deleted from the database. Database consists of two columns: username and room. Database side works fine.

onlinelar.php:

<?php

$data = array();

        $current = $_GET['current'];

        $room = $_GET['room'];

        $getRoomUsers = mysql_query("SELECT * FROM `chat_users_rooms` WHERE `room` = '".$room."'");

        if(mysql_num_rows($getRoomUsers) != $current)
        {
            $data['numOfUsers'] = mysql_num_rows($getRoomUsers);    
        }
        else
        {
            $data['numOfUsers'] = $current; 
        }
        echo json_encode($data);

?>

online.js:

var numOfUsers = 0;
var room;

function chat(room2)
{
room = room2;   
}

$.ajaxSetup({
    cache: false 
});


function getuserlist() {


     $.ajax({
        type: "GET",
        url: "onlinelar.php",
        data: {  
                'room': room,
                'current' : numOfUsers
              },
        dataType: "json",
        cache: false,
        success: function(data) {
                if (numOfUsers != data.numOfUsers) {
                numOfUsers = data.numOfUsers;

                $('#bu').html($("<strong id='bu'>"+ numOfUsers + "</strong>"));
            }




            setTimeout(getuserlist(),1);

        },
    });

}

And finally, the initializer of it in index.html:

----something

       <script type="text/javascript">

                var chat = new Chat(<?php echo $room;?>);
                chat.getuserlist();

            </script>
                      <strong id="bu">
                        <?php
                        echo $numOfUsers;
                        ?>
                        </strong>

------something

In here, i want to check database situation(rows of the certain room), and change the number of chatters in that room simultaneously. 'current' is for number of users and 'room' is for the name of the room.But there is no change even though the num of rows of database is changing. Which part i am missing? Note: I have added online.js in index.php

$('#bu').html($("<strong id='bu'>"+ numOfUsers + "</strong>"));

This line places a new element under your old one, what you want to do is replace the old one by calling

$('#bu').html(numOfUsers);

Also setTimeout() takes milliseconds so 1 is a really low value, you might want to start with 1000 and work from there.

Edit: And setTimeout() takes a function as a param so you want to call:

setTimeout(getuserlist, 1000);

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