Okay so to make a long story short I am using this script in a jquery mobile envoirment. I am using ajax in it to grab results from the database. I currently works, however it does not refresh automatically. I have read numerous online posts about how to use the set interval function and I have tried that. However when I try it, it works, but it keeps adding duplicate content( the same database record over and over again). I just can’t seem to get this to work. Any help would be much appreciated, thanks in advance!
Here is my code (*not I removed the setinterval function):
<script type="text/javascript">
$( document ).delegate("#member_home", "pagecreate", function()
{
var member= new Array();
$.ajaxSetup({cache: false})
$.ajax({
url: '/scripts/alert_display.php',
data: "",
isajax: 1,
dataType: 'json',
success: function(data)
{
$.each(data, function(key, val) {
var friend = val['friend'];
$('#member_alerts').append(friend+" Wants to be your friend<input type='hidden' value='"+friend+"' id='hidden4' /><button type='submit' id='add'>Accept</button><br />");
});
}
});
})
</script>
Thank you so much for the help, so just to be clear, my code should now look like this?:
<script type="text/javascript">
$( document ).delegate("#member_home", "pagecreate", function()
{
var refreshId = setInterval(function()
{
var member= new Array();
$.ajaxSetup({cache: false})
$.ajax({
url: '/scripts/friend_request_display.php',
data: "",
isajax: 1,
dataType: 'json',
success: function(data)
{
$.each(data, function(key, val) {
var friend = val['friend'];
$('#member_alerts').html(friend+" Wants to be your friend<input type='hidden' value='"+friend+"' id='hidden4' /><button type='submit' id='add'>Accept</button><br />");
});
}
});
}, 1000);
})
</script>
It keeps adding duplicate content because you’re using the
appendfunction, which adds to the current DOM in the element. Usehtmlinstead (you may also need to create the div tags). See this SO question for more info.