1

I'm trying to finish an who's online script but I am running into some issues with repeating usernames with my auto refresh function. Is there a way in jQuery to find previous values returned and if found, skip showing duplicate usernames?

Here is my code:

$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "/members/groups/get-one-group-members-online/" + location.pathname.split("/")[4],
        dataType: "json",
    }).done(function(msg) {
        $.each(msg.display_name, function(i, item) {
            $("#members-online").append(msg.display_name[i] + "<br>");
        });
    }).fail(function() {
        $('#members-online').html("Error retrieving online group members");
    });
});

function reloadElement() {
    $.ajax({
        type: "GET",
        url: "/members/groups/get-one-group-members-online/" + location.pathname.split("/")[4],
        dataType: "json",
    }).done(function(msg) {
        $.each(msg.display_name, function(i, item) {
           // how to not show repeating values?
           $("#members-online").append(msg.display_name[i] + "<br>");
        });
    }).fail(function() {
        $('#members-online').html("Error retrieving online group members");
    });
}

setInterval(function() {
    reloadElement()
}, 5000);

and the actual html element:

<p id="members-online"></p>

Any help would be appreciated. I can try and add more information if it my question is unclear.

Thanks!

1 Answer 1

1

Given that you're performing the exact same logic in both situations the logic can be simplified. Instead of appending to the element when the call is made, just rebuild the whole element by either calling empty() on it first, or setting it's html().

If you then extract the logic to a function you can call it both on load and every N seconds. Try this:

$(function() {
  function buildOnlineMemberList() {
    $.ajax({
      type: "GET",
      url: "/members/groups/get-one-group-members-online/" + location.pathname.split("/")[4],
      dataType: "json",
    }).done(function(msg) {
      var displayNames = msg.display_name.join('<br />');
      $("#members-online").html(displayNames);
    }).fail(function() {
      $('#members-online').html("Error retrieving online group members");
    });
  }

  setInterval(function() {
    buildOnlineMemberList(); // call on interval
  }, 5000);
  buildOnlineMemberList(); // call on load
});

You should however note that AJAX polling is considered an anti-pattern. You would be much better to use WebSockets which update the connected clients when a new member comes online, or goes offline. Their name can then be added or removed as needed.

1
  • It still needs to go in the document.ready handler, but would replace your old code. I'll update it to give you the whole thing. Commented Apr 7, 2017 at 15:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.