Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

326
Visualizações
Auto refresh div on new message Node js

Hi I am making a simple chat website with node js. I want everyone to see posted messages. The messages are stored in a array and then displayed on the website. The problem is that if I post the message the others wont see the message until a new one is posted. I somehow need to refresh the div where the messages are displayed. I tried using jquery but it didnt work for me. Can some one help?

const http = require('http');
const { Socket } = require('socket.io');
const WebSocketServer = require('websocket').server;
var steviloSporocil = 0;
let sporocila=[];

const server = http.createServer();
console.log('Server is on port 3000')
server.listen(3000);

const wsServer = new WebSocketServer({
    httpServer: server
});

wsServer.on('request', function(request) {
    const connection = request.accept(null, request.origin);

    connection.on('message', function(message){
        sporocila.push(message.utf8Data);
        connection.sendUTF(JSON.stringify(sporocila));
        console.log('Received Message:', JSON.stringify(sporocila));
    });

    connection.on('close', function(reasonCode, description) {
        console.log('Client has disconnected.');
    });
});
<?php ob_start() ?>
    <?php 
        $titel="Chat"; 
        $nekaj=$_SESSION['uporabnik'];
    ?>
    <div class="chat-main" id="text"></div>

    <form name='form' method='post' class="form">
        <div class="form-group">
            <input type="text" class="form-control" id="textbox" name="chat" placeholder="Chat">
            <button type="button" class="btn btn-primary" name="gumb" id="gumb" onclick="Poslji()" autocomplete="off">Send</button>
        </div>
    </form>
    <script>
        var myInput = document.getElementById("textbox");
        var up='<?php echo $nekaj; ?>';
        function Poslji(){
            if(myInput && myInput.value){
                const ws = new WebSocket('ws://localhost:3000'); 
                ws.onopen = function(){
                    ws.send(up+": "+document.getElementById('textbox').value+"<br>");
                };
            
                ws.onmessage = function(e) {
                    const arr=JSON.parse(e.data);
                    console.log("Received: '"+e.data+"'");
                    document.getElementById('text').innerHTML=arr;
                };
            }   
        }
    </script>
<?php 
    $content=ob_get_clean();
    require "layout.html.php";
?>

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda