I got an auto-refresh snippet of code called News feed master and I have managed to implement and customize it to my own taste. Everything seems to be working except the auto-refresh which is meant to show my new post as I input it instead of having to refresh the whole page.
Here is a section of my index.php that queries the database for new feeds
<?php
/**
* Preparing and getting response for latest feed items.
**/
if(isset($_POST['latest_news_time'])){
$result = $db->query("SELECT *
FROM users U, messages M WHERE U.user_id = M.uid_fk AND M.created > '".$_POST['latest_news_time']."' ORDER BY M.created DESC");
$current_time = $_POST['latest_news_time'];
$item = $db->fetch_assoc($result);
$last_news_time = $item['created'];
while ($last_news_time < $current_time) {
usleep(1000); //giving some rest to CPU
$item = $db->fetch_assoc($result);
$last_news_time = $item['created'];
}
?>
<li id="<?=$item['created']?>">
<div class="liSub">
<div class="feed_image"><img src="uploads/user/<?=$item['image']?>" alt="<?=$item['image']?>"></div><!-- image -->
<div class="head"><a href="profile.php?user=<?=$item['username']?>"><?=$item['first_name']?> <?=$item['last_name']?></a><?php if($item['status']=='politician')print"<img src='images/tick.png' alt='verified' class='verified'>";?></div><!-- username -->
<div class="feedtext"><span><?=$item['message'];?></span></div><!-- message -->
<div class="bottom">
<p><?=$item['like_count']?></p><a href="#"><img src="images/Like-button.png" alt="like" class="like"></a><!-- like -->
<p><?=$item['dislike_count']?></p><a href="#"><img src="images/disLike-button.png" alt="dislike" class="dislike"></a><!-- dislike -->
<p><?=$item['comment_count']?> Comment(s)</p><!-- comments -->
</div>
</div>
</li>
<?php
exit;
}
?>
And here's a section of my javascript that is supposed to perform the auto-refresh
/**
* Function to update the news feed
**/
function updateFeed(){
var id = 0;
id = $('#feeds li :first').attr('id');
$.ajax({
'url' : 'index.php#feeds ul',
'type' : 'POST',
'data' : {
'latest_news_time' : id
},
success : function(data){
setTimeout('updateFeed()', 1000);
if(id != 0){
$(data).prependTo("#feeds ul");
}
}
})
}
I would be glad if you could help spot out the problem. I'm not a pro in jquery at all so it's giving me sleepless nights. Thanks.