Reputation: 3
Using the codes below, I want to update the leaderboard <div id='result'></div>
whenever the score (json) changes in score.php
.
I tried wrapping the whole $.getJSON
query with setInterval
but its duplicating the list items everytime the setInterval
fires instead of just updating the list items with the new score json object.
So far , the code works when you refresh the page but I want it to update dynamically.
Any ideas how to achieve the desired effects that I want? TIA
index.php
<div id='result'></div>
script.js
$(document).ready(function(){
$('#result').html('<ul></ul>');
setInterval(function(){
$.getJSON('score.php', function(data){
$.each(data, function(i){
$('#result > ul').append('<li>'+i+' : '+data[i]+'</li>');
});
});
},1000);
});
score.php
<?php
$result = [
"player1"=>5,
"player2"=>20,
"player3"=>7
];
arsort($result);
echo json_encode($result);
// output
player2 : 20
player3 : 7
player1 : 5
note: I have modified script.js to show the problem. the issue is that every time setInterval
fires up, the list- items is duplicating which is not what i want.
really all i want is that the original list items will just update to reflect the changes in score.php everytime a player gets higher score, it shows in the leaderboard.
UPDATE: this is already resolved as per @Peekayy and @user26409021 answers below. but I don't know which one is more efficient so I will leave this question for a couple of days to gain more votes for the two answers and then I will choose an answer. thanks guys ;)
Upvotes: 0
Views: 1026
Reputation: 7288
What you really need isn't .append
but .html
which will remove previous element from the div.. By doing so, you won't have duplicate entries.
$('#result').html('<ul></ul>');
setInterval(function(){
$.getJSON('score.php', function(data){
$('#result').html('<ul></ul>');//reset here..
$.each(data, function(i){
$('#result > ul').append('<li>'+i+' : '+data[i]+'</li>');
});
});
},1000);
Upvotes: 0
Reputation: 56
For each setInterval you append new <li>
items corresponding to the JSON result. This without clearing the existing nodes. That's why it seems to be duplication items.
You have to clear the #result children with $('#result > ul').empty(); before adding the new nodes.
$(document).ready(function(){
$('#result').append('<ul></ul>');
$.getJSON('score.php', function(data){
$('#result > ul').empty();
$.each(data, function(i){
$('#result > ul').addClass('result-list').append('<li>'+i+' : '+data[i]+'</li>');
});
});
});
Also, i wonder if the use of addClass('result-list')
for each player score is relevant. You should do it only once i think to make it cleaner.
Final code i'd suggest :
$(document).ready(function(){
var resultList = $('#result').append('<ul></ul>');
resultList.addClass('result-list');
setInterval(function(){
$.getJSON('score.php', function(data){
resultList.empty();
$.each(data, function(i){
resultList.append('<li>'+i+' : '+data[i]+'</li>');
});
});
}, 30000);
});
Upvotes: 1