Reputation: 1451
Currently I'm using this function, but it can only refresh the whole #comments div.
$.ajax({
url: 'WebForm1.aspx',
success: function (data) {
$("WebForm1.aspx #comments").html(data);
}
});
I'm trying to figure out if jQuery AJAX can detect any difference between what the user is actively viewing a webpage, and what is coming from the database, so whenever someone adds a comment, the visitors see the incoming comment as fading in, rather than the whole #comments div getting refreshed periodically.
Here is the workflow that I wish:
AJAX request 1 -> jquery fetches Data A , Data B , Data C and displays them in the #comments on the browser, saves it in its cache.
(Data D is added into the db a few while later)
AJAX request 2 -> jquery fetches Data A , Data B , Data C and Data D, compares with the cache on the browser and detects that Data D was absent in the previous version of #comments, and fades in only the new Data D.
How can I do this? Please help. Thanks.
Upvotes: 0
Views: 87
Reputation: 3000
Neither jQuery nor jQuery.ajax are able (or meant) to do what you're asking. The comparison logic must be done by yourself.
I have a couple of suggestions:
Hope that helps you get on the right track.
Upvotes: 2
Reputation: 20747
You will need some sort of setInterval to continuously figure out what the latest comment was and fetch new data after the newest comments' ID
JS
// check every ten seconds
setInterval(function() {
// figure out most recent comment and pass it to the URL so your query can search for anything greater than newest_comment
$.ajax({
url: 'WebForm1.aspx',
type: 'GET',
data: {'newest_comment':$('#comments').find('span.comment:eq(0)').data('comment_id')}, // newest_comment would be 5
dataType: 'HTML',
success: function (data) {
$("#comments").prepend(data);
}
});
}, 10000);
Possible HTML
<div id="comments">
<span class="comment" data-comment_id="5"></span>
<span class="comment" data-comment_id="4"></span>
<span class="comment" data-comment_id="3"></span>
<span class="comment" data-comment_id="2"></span>
<span class="comment" data-comment_id="1"></span>
</div>
Upvotes: 0