How could I refresh data on my chat page lively, when i’m using MySQL database with php?
I think, the best way to do this could be saving last loaded message and then, when someone send new one, load only this new message.
I am loading data(currently not live) this way:
include '../connection.php';
include 'verifyLogin.php';
if (!checkUserLogin()) {
echo "User not logged";
return;
}
$chat = $_POST['chat'];
if (!$chat || empty($chat) || $chat === null) return; //check is data valid
$toReturn = new stdClass();
$sql0 = 'SELECT COUNT(*) AS 'count' FROM chat_chats cc,chat_userchats cu WHERE cc.code=:code AND cc.CODE = cu.CHAT_CODE AND cu.USER_ID = :id;';
$stmt0 = $conn->prepare($sql0);
$stmt0->bindParam(':code', $chat);
$stmt0->bindParam(':id', $_SESSION['ID']);
$stmt0->execute();
$row = $stmt0->fetch(PDO::FETCH_ASSOC);
$isUserMember = $row['count'] > 0 ? true : false;
$toReturn->isMember = $isUserMember; //checking is user member of chat
if($isUserMember){
$sql = 'SELECT cc.MESSAGE AS "MSG",cc.SEND_TIME AS "TIME",cu.USERNAME AS "SENDER" FROM chat_conversations cc, chat_users cu WHERE cc.CODE=:code AND cu.ID = cc.SENDER_ID ORDER BY 2 DESC;';
$stmt = $conn->prepare($sql);
$stmt->bindParam(':code', $chat);
$stmt->execute();
$messagesArray = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$messagesArray[] = $row;
}
$toReturn -> chatMessages = $messagesArray;
$toReturn -> chatMessagesAmount = count($messagesArray);
}
echo json_encode($toReturn);
To load it into chat box im using AJAX:
function loadMessages() {
if (!getCurrenCode() || getCurrenCode() === null) return;
$.ajax({
type: 'post',
url: 'actions/getMessages.php',
data: { chat: getCurrenCode() },
beforeSend: () => {
CHAT_MESSAGE_WRAPPER.innerHTML = null;
CHAT_MESSAGE_WRAPPER.appendChild(loading);
},
success: (resp) => {
console.table(resp);
CHAT_MESSAGE_WRAPPER.innerHTML = null;
CHAT_AREA.innerHTML = null;
if (!resp || resp === null) return;
var response = JSON.parse(resp);
var msgs = response.chatMessages;
if (!msgs || msgs === null) return;
for (var i of msgs) {
CHAT_AREA.appendChild(generateMessageBox(i['MSG'], formatDate(new Date(i['TIME'])), i['SENDER']));
}
if (response.chatMessagesAmount < 1) {
CHAT_MESSAGE_WRAPPER.appendChild(noMessages);
}
setCurrentChatActive();
}
})
}
Thank you in advance!
2
Answers
I am trying to use nodejs in this app, but i can't find out how to correctly import css into ejs file using express. On first request to page css is loading correctly, but on another ones it completly doesn't load.
file structure: tree
login.ejs
content(sorry for mixing abbs)
I don’t recommend this but you can try making a function that has setTimeout(), like this: