I need a suggestion with live update messages, here is my code:
<script>
function fetch_messages(){
var user_id = "1" // example id
$.ajax({
url: "do_fetch.php",
type: "POST",
data: { user_id : user_id },
dataType: "json",
success: function(data) {
for (var i = 0; i < data.length; i++) {
$("#messages_list").append('<div id="'+data.id+'">'+data.message+'</div>');
}
setTimeout("fetch_messages()", 3000);
}
});
}
$(function(){
fetch_messages();
});
</script>
and there is div messages:
<div id="messages">
</div>
php code:
<?php
include('connection.php')
$user_id = $_POST['user_id'];
$my_id = $_SESSION['user_id'];
$sql = 'SELECT * FROM messages WHERE user_id = '.mysql_real_escape_string($user_id).' AND my_id = '.mysql_real_escape_string($my_id);
$result = mysql_query($sql, $connection);
echo json_encode($result);
?>
This code works, but I don’t want to read all messages and show them, I need to load only new messages, so how should I do that? Do I need to put a hidden field with timestamp and to check with ajax for time later than that?
First you load with ajax just 20 messages in a ul
Then get the last message id to get the date.
you can have a click button to load more.
In the php file you select the messages with date > message_date with limit 30.
You can pass the user id too.