Let say i have 15 or more posts in one page. The code inside the while loop look like this
<div class="post" id="<?php echo $postID?>">
<h1><?php echo $title;?></h1>
<div class="postmeta">
posted by <?php echo $author;?> , <?php echo timeAgo($postDate);?></div>
</div>
this is just an a example ! So timeAgo() function convert the unix timestamp 1329569847 to human time 11 mins ago. And how to make it synchronize in real time with ajax I mean after 5 mins to change to 16 mins ago,after 4 mins to change to 20 mins ago and that to effect all posts.
So i managed to make it work thanks to chenio and TheShellfishMeme (beer).
And this is the code that do the magic
<span class="timestamp" id="5" postdate="1329576793"></span><br/>
<span class="timestamp" id="8" postdate="1329576795"></span><br/>
<script>
updateTimestamps();
setInterval(updateTimestamps, 60000);
function updateTimestamps(){
$(".timestamp").each(function(i){
var timestamp = $(this).attr("postdate");
var postID = $(this).attr("id");
$.ajax({
type: "POST",
url: "myURL",
data: "postID="+ postID +'×tamp=' + timestamp,
cache: false,
success: function(html){
$(".timestamp#"+postID).html(html);
}
});
});
}
</script>
I’d use data attributes like here http://jsfiddle.net/rXFnn/ to add the unix timestamp to a span inside the div which is meant to contain the ‘time ago’ string.
Then you port your timeAgo logic over to javascript and update it every minute using setInterval.
No need to do AJAX for something that simple, but note that the example below uses jQuery.
For completeness, here is the code again: