How to fadeIn new results to jQuery AJAX autoupdating div
I have a div that is populated with an external php file, that loops results from a MySQL query. I would like the div to refresh every 5 seconds using AJAX, and have only the new results fade in at the top of the list, while the others just move down, like Twitter and Facebook.
I am new to AJAX, and this is what I have now in the head of my document:
<script type="text/javascript">
$(document).ready(function(){
$('#load_tweets').load('inc/searchresults.php');
});
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('inc/searchresults.php').fadeIn(5000);
}, 5000); // refresh every 5 seconds
</script>
Right now, the content does not load on document ready, but all of the div does refresh every 5 seconds, however it does not fade in. I have three questions, first, how can I fix my code so that the div loads on page load? Second, how can I get it to fade in properly?
Finally, how would I go about only fading in the new results? I'm thinking it would involve fading in items with a primary key > the ones from the previous AJAX call, but I'm not sure how to do that.
Thank you 开发者_如何学Govery much for your assistance.
Because you're calling the fadeIn
function asynchronously, it's running at the same time as the load and not having time to complete before it gets called again. Also, you're never fading out. Try this:
<script type="text/javascript">
$(document).ready(function()
{
function update_div()
{
$('#load_tweets').fadeOut('normal', function()
{
$('#load_tweets').load('inc/searchresults.php');
$('#load_tweets').fadeIn(5000, function()
{
window.setTimeout("update_div()", 5000);
});
});
}
update_div();
});
</script>
The trick is to not load all the content again, simply insert the new content above hidden and then add fade it in.
// Untested, written here without syntax.
var timeSinceUpdate = <?php echo(time()); ?>; //Needs to be system time so that it works correctly
$(document).ready(function(){
setInterval(function(){
$.get('inc/queriesSince.php?searched=something+something×inceupdate=' + timeSinceUpdate , function(data){
alert(data);
if(confirm('Add new Data to screen?'))
{
//Add Stuff to DOM and
//update the timeSinceUpdate from the data recieved so that it is system time.
}
});
}, 3000);
});
精彩评论