I am using a PHP Ajax solution for my chat within my web application. The chat looks very neat, however I am running into a big problem when inside the chat room. I am using a setInterval
to get new messages but when the interval runs every second the page ends up jumping to the very first message. This happens every single second preventing the user from seeing the latest message. Here is the script I am running:
<?php
$id = $_GET['id'];
echo
"<script>
function ajax() {
var req = new XMLHttpRequest();
req.onreadystatechange = function () {
if(req.readyState == 4 && req.status==200){
document.getElementById('content').innerHTML = req.responseText;
}
}
req.open('GET', 'process.php?id=$id',true);
req.send();
}
setInterval(function () {
ajax();
}, 1000);
</script>
";
?>
Here is my HTML where the content is being loaded:
<div class="card bg-sohbet border-0 m-0 p-0" style="height: 100vh;">
<div id="sohbet" class="card border-0 m-0 p-0 position-relative bg-transparent" style="overflow-y: auto; height: 100vh;" onload="ajax();">
<div id="content"></div>
</div>
</div>
I have tried using setTimeout/clearTimeout
, event.preventDefault()
and return false;
. None of these solutions have worked. If you could help it would be greatly appreciated.
Please checkout this video link for an example: https://www.hippovideo.io/video/play/gO83luY-81NfIeSeltBW-Q