I'm trying to clear elements in a ul list before its populated i.e. want to refresh (delete and load) a ul list everytime using ajax calls, but for some reason its not working, the code is as below
<div id="activitycontainer"> <ul id="activitylist" style="list-style: none;padding:0; margin:0;"> </ul> </div>
$(document).ready(function() {
setInterval(function() {
autoRefreshCommentsHomePage()
}, 5000);
});
function autoRefreshCommentsHomePage() {
$.ajax({
url: 'GetActivity.sc',
success: function(data) {
$(#activitylist).empty();
var resultStr = data;
var str = '';
var temp = '';
var ele = resultStr.split('@!@');
var arrayLength = ele.length;
for (var i = 1; i < arrayLength - 1; i++) {
temp = '<li><a href="#">' + 'User1' + ' @</a><span> </span><a>' + ele[i] + '</a></li>';
$(temp).appendTo("#activitylist");
i = i + 1;
temp = '<li><a style="color: black;">' + ele[i] + '</a></li>';
$(temp).appendTo("#activitylist");
temp = '<li style="float: right;"><a href="#">Comment</a><span> </span><a href="#">Like</a><span> </span></li><br>';
$(temp).appendTo("#activitylist");
temp = '<br>';
$(temp).appendTo("#activitylist");
}
;
}
});
};
I'm clearing the activitylist
ul using .empty function, when i run this what is happening is that no data gets populated in the ul.
If i remove the .empty function call, then the ajax keeps loading data every 5 seconds and my list keeps on growing but I want to basically clear the existing data and then load, this is not happening.
Please advise.
My advice would be to simply replace the full block of HTML, rather than removing/adding in two separate steps. Use the jQuery html() method for this.
function autoRefreshCommentsHomePage() {
$.ajax({
url: 'GetActivity.sc',
success: function(data) {
// Off topic, but you only need one var statement to declare all these
var resultStr = data,
str = '',
temp = '',
ele = resultStr.split('@!@'),
arrayLength = ele.length;
for (var i = 1; i < arrayLength - 1; i++) {
// Note the variable change to +=
temp += '<li><a href="#">' + 'User1' + ' @</a><span> </span><a>' + ele[i] + '</a></li>';
i = i + 1;
temp += '<li><a style="color: black;">' + ele[i] + '</a></li>';
temp += '<li style="float: right;"><a href="#">Comment</a><span> </span><a href="#">Like</a><span> </span></li><br>';
temp += '<br>';
}
// Replace it all at once
$('#activitylist').html(temp);
;
}
});
}
;