skip to Main Content

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


  1. Chosen as BEST ANSWER

    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.

    const express = require('express')
    const app = express()
    const port = 8080
    
    
    app.use(express.static('public'));         //static - public 
    app.use('/css', express.static(__dirname + 'public/css'));  //static - css
    app.use('/js', express.static(__dirname + 'public/js'));   //static - js
    app.use('/img', express.static(__dirname + 'public/img'));  //static - img
    
    app.set('views', './views');
    app.set('view engine', 'ejs');
    
    app.get('/login', (req,res) => {
      res.render('login')
    })
    app.get('/register', (req,res) => {
      res.render('register')
    })
    app.get('/', (req,res) => {
      res.render('index')
    })
    
    app.listen(port, () => {
      console.info(`[APP] running on port: ${port}`)
    })
    

    file structure: tree

    login.ejs content

    
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Logowanie</title>
        <link rel="stylesheet" href="css/mainLogRegStyle.css">
        <link rel="stylesheet" href="css/loginStyle.css">
        <script src="https://kit.fontawesome.com/58fefbd958.js" crossorigin="anonymous"></script>
        <link rel="shortcut icon" href="../img/login-icon.png" type="image/x-icon">
    </head>
    
    <body>
        <div class="container">
            <form id="loginForm" autocomplete="off" method="POST">
                <div class="formHeader">
                    <h1>logowanie</h1>
                </div>
                <div class="content">
                    <div class="messageContaier">
                        <div id="messageBox"></div>
                    </div>
                    <div class="line"><i class="fa-solid fa-user icon"></i><input placeholder="Login" name="login" type="text" id="username"></div>
                    <div class="line"><i class="fa-solid fa-key icon"></i><input placeholder="Hasło" name="passwd" type="password" isHidden="true" id="password" class="password"><i id="showhide" class="fa-solid fa-eye show-hidePass"></i></div>
                    <input type="submit" id="submit" value="Zaloguj">
                </div>
                <p class="bottomText">Nie masz jeszcze konta? <a href="../register/">Załóż je!</a></p>
            </form>
        </div>
    </body>
    
    </html>
    

    (sorry for mixing abbs)


  2. I don’t recommend this but you can try making a function that has setTimeout(), like this:

    loadMessages();
    function loadMessages(){
       setTimeout(function(){
          // ajax code for getting messages here
       }, 1000)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search