0

I'm trying to list out recently active users via JSON/jQuery. However, this counting system is not working as it should. It both lists out the users and gives a "No active users" message. How could I fix this?

Thanks!

PHP code that grabs the active users:

$liveView_single = array();
$liveView_array = array();

while ($row = mysqli_fetch_assoc($result)){
    extract($row);

    $liveView_single['id'] = $id;
    $liveView_single['type'] = $type;
    $liveView_single['username'] = $username;
    $liveView_single['lastip'] = $lastip;
    $liveView_single['lastactivitypage'] = $lastactivitypage;

    $liveView_full[] = $liveView_single;
}

echo(json_encode($liveView_full));
?>  

jQuery that grabs the JSON elements

<script type="text/javascript">

//counter for number of JSON elements
var i=0;        

//show active users function
function showActiveUsers(){
$('#content').html('');
$('#noActiveUsers').html('');

$.get("array.php", function (activeUsersList) {
        $.each(activeUsersList, function (a, b) {
            $("#content").append("<tr class=\"userRow\" style=\"display:none\">" +     "<td class=\"userId\">" + b.id + "</td>" 
                       "<td class=\"type\">" + b.type + "</td>"
                       "<td class=\"username\">" + b.username + "</td>"
                       "<td class=\"lastip\">" + b.lastip + "</td>"
                       "<td class=\"lastActivityPage\">" + b.lastactivitypage + "</td>" + "</tr>");

            $(".userRow").show();               
    //add to counter of JSON elements
    i++;
    });     
        }, "json");
        if (i == 0){
            $('#heading').hide();
            $('#noActiveUsers').append('<h2>There are no active users.</h2>');
            $('#noActiveUsers').show('slow');
        }

        //reset timer
        setTimeout("showActiveUsers()", 3000);
    }

    $(document).ready(function() {
        showActiveUsers();
    });

</script>
1
  • Why is everybody voting against this question? It formats correctly on my end - but now accepted the corrections from @dakshbhatt21 Commented Jul 13, 2013 at 12:12

1 Answer 1

1

Ajax requests are, by default, executed asynchronously (hence the name ajax). The script make an ajax request to the server, and immedeatelly continue with the script (if(i==0)). When the data is ready, it'll continue with the success function (function (activeUsersList)). To fix this you could make the ajax request synchronous (but in this case there is no reason to; see the docs how to do that). The other way is moving the "no users online message" into the callback function. This is more logical, because you need the data from the ajax request to properly determine if there are users online.

In the following example I removed i and added moved your if (i == 0) block up into the callback function.

$.get("array.php", function (activeUsersList) {

    $.each(activeUsersList, function (a, b) {
            $("#content").append("<tr class=\"userRow\" style=\"display:none\">" +
                                        "<td class=\"userId\">" + b.id + "</td>" + 
                                        "<td class=\"type\">" + b.type + "</td>" + 
                                        "<td class=\"username\">" + b.username + "</td>" +
                                        "<td class=\"lastip\">" + b.lastip + "</td>" +
                                        "<td class=\"lastActivityPage\">" + b.lastactivitypage + "</td>" +

                                "</tr>");
            $(".userRow").show();

            //add to counter of JSON elements
    });

    //Move this into the callback function.
    if( activeUsersList.length == 0 ) {
        $('#heading').hide();
        $('#noActiveUsers').append('<h2>There are no active users.</h2>');
        $('#noActiveUsers').show('slow');
    }


}, "json");
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks - but it just keeps the heading of the table. Doesn't do anything within the IF statement. And how could I add a counter for JSON elements? Simply because I would need to monitor changes in the count... Thanks!
activeUsersList.length contains the amount of entries in your json list. This is equal to the amount of people online if I read your code.
I used the exact same code as you provided above - but the IF block doesn't execute when there are no active users... any idea why? EDIT my bad...the PHP had a typo... thank you! Can you tell me how could I use that 'activeUsersList.lenght' to compare whether the number has increased/decreased?
Sorry - not sure I understand. Could you possibly give me the code for that - would be very much appreciated. The JSON generates a '[]' when no users are online.
I suppose you can use .data() for that. Store activeUsersList.length in a custom key on the element, and retrieve it the next time you check for active users. You can't use that between two page-loads, but you could use that if you check it, for example, every 5 minutes within 1 page load.

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.