I have asked this question before also, but the solution didn’t work. I have a messaging website. I fetch the messages via AJAX with Java Script that runs per 1 second. The problem is that it fetch all the values from starting to end. So I thought of passing the last message ID via AJAX. But I don’t know how to use that value in the Java Script, so that I can use it to fetch the messages which will be more than it.
Also I want the div to be in it’s bottom position, until the user scrolls it. And whenever a new message is fetched the div should automatically reach the bottom.
Here is my CSS, HTML, Java Script and AJAX code:
<style>
.readarea{
padding: 10px;
margin-top: 10px;
background-color: #FFFFFF;
height: 450px;
overflow-x: hidden;
}
</style>
<body>
<div class="readarea" id="readarea">
<!--Messages is to be displayed here.-->
</div>
<div class="inputarea">
<textarea placeholder="Type your message" style="width: 800px; overflow: hidden" id="msg"></textarea>
<input type="submit" value="Send" style="padding: 10px 25px" id="sendmsg">
</div>
</body>
<script>
function fetchdata(){
var lm = //last message ID
var cuser = //user ID of the 1st person
var ouser = //user ID of the 2nd person
$.ajax({
url: "readmessagesprocess.php",
type: "POST",
data : {cuser:cuser, ouser:ouser, lm:lm},
success: function(read){
$("#readarea").html(read);
}
});
}
$(document).ready(function(){
setInterval(fetchdata,1000);
});
</script>
Here is my PHP code to fetch the messages:
<?php
$cuser = mysqli_real_escape_string($conn,$_POST['cuser']);
$ouser = mysqli_real_escape_string($conn,$_POST['ouser']);
$lastmessage = mysqli_real_escape_string($conn,$_POST['lm']);
$sql = "SELECT id, fromid,message,toid FROM messages WHERE ((fromid={$cuser} AND toid={$ouser}) OR (fromid={$ouser} AND toid={$cuser})) AND id>{$lastmessage}";
$result = mysqli_query($conn, $sql) or ("Query Failed");
while($row=mysqli_fetch_assoc($result)){
if($row["fromid"]==$cuser){
echo "<div class='cuser'>".$row["message"]."</div>";
}else{
echo "<div class='ouser'>".$row["message"]."</div>";
}
$lm = $row["id"]; //last message id
}
?>
Here I want the $lm("lm") to use in Java Script as the last message ID (var lm) and the rest of the code to concatenate in the . Also I want this div to be in the bottom part when the page loads or new message is fetched.
2
Answers
I have turned your code into a working chat-snippet. I am using a slightly quirky method for mimicking an external PHP server, that would be handling the actual chat data in a database. I realize that parts of my script will seem terse and even cryptic. So, here are a few rudimentary explanations:
The code starts with an IIFE, an "immediatel invoked functional expression". This expression provides a scope for setting up a "chat database", i. e. the object
msg
with a first message in it. Thismsg
object is visible for the functionssetmsg()
andgetmsg()
which I also define in the same scope throughw[setm]=...
(w
andsetm
are arguments of the IIFE and set towindow
and'setmsg'
when the IIFE is called) andw[getm]=...
.The function
qs()
is simply a shorthand notation for callingdocument.querySelector()
which I find a bit clunky to hanlde. The optional argumentel
makes it possible to search within an element context. Without it the search starts on the document level.Oh, yes, and the
blb()
function is a little trick I picked up here. Stackoverflow does not provide a way of doing CORS Ajax calls and this method is a workaround that allows at leastGET
calls (you cannotPOST
to theURL.createObjectURL()
object). The functionsgetmsg()
andsetmsg()
use thisblb()
utility to mimick an external server. They return an object that can be used in place of a server-URL that is usually supplied in the jQuery Ajax call.A few word on how the chat system works: the regular message scan starts once the page is loaded with
scanStart()
. This function in turn callsfetchdata()
which will try to find theid
of the latest post that is already shown on the browser. I used the CSS selector"li:last-child"
for this purpose. Unlike in the original version I am using<li>
elements for each post here. And the above selector will get the last one posted. I then grab its id and put it inlm
(lm
is always the message index of the last message found inmsg
plus 1) and start the$.ajax()
call togetmsg()
withlm
.The buttons
[stop]
and[resume]
can be used to stop and resume the message scanning.this shouldn’t be done via AJAX, but with sockets. have your favourite websearch give you results for "nodejs chat"