I'm writting a very simple chat application. I have written a code that works at inserting data in database without refreshing the page. But when I test with two users at the same time, I can only see what the other user sent to me when I send a new message. How can I make it more live? I spent the entire day reading on Websockets (specifically socket.io, ratchet) and long-polling. I found interesting solutions around here but I'm looking to implement it with the code I have already written and it's confusing me. I'm using a php while statement to get data from database.
Working Ajax code
<script>
$(document).ready(function(){
$("#buttons").click(function(){
var fromuserid = $("#fromUserId").val();
var touserid = $("#toUserId").val();
var chatMessage = $("#chatMessage").val();
// stored in database.
var dataString = 'fromUserId='+ fromuserid + '&toUserId='+ touserid + '&chatMessage='+ chatMessage;
// AJAX
$.ajax({
type: "POST",
url: "chat.php",
data: dataString,
cache: true,
success: function(response){
$("#displayMessage").html(response);
$("#chatForm").trigger("reset");
}
});
return false;
});
});
</script>
while statement
<div id='displayMessage' style='height: 480px; padding:5%; overflow-x:hidden;'>
<?php
$chatmsgQ="SELECT * FROM ve_chat c
WHERE c.isActive='1' AND (c.fromUserId='$loginid_session'
OR c.toUserId='$loginid_session')";
$chatmsgresult= mysqli_query($db,$chatmsgQ);
while($chatmsg= mysqli_fetch_array($chatmsgresult)){?>
<?php if($chatmsg['fromUserId']==$loginid_session):?>
<!-- user one -->
<p class='bubble pull-left'><?=$chatmsg['message'];?></p>
<?php elseif($chatmsg['fromUserId']!=$loginid_session):?>
<!-- user two-->
<p class='bubbleother pull-right'><?=$chatmsg['message'];?></p>
<?php endif;?>
<?php } ;?>
</div>