I want to add the function of chatting with a customer on WhatsApp through my website. In other words, the employee logs into the website and responds to the customer through the form and receives the customer's response. The problem is that I have to reload the page to see the updated customer response. This conversation is being saved in the database. To display this conversation, I search the database for messages. The problem is that the form does not update itself when I receive a new message in the database. I use the following code to display this conversation:
<!-- DIRECT CHAT -->
<!-- Conversations are loaded here -->
<div class="direct-chat-messages" style="height: 500px; overflow-y: auto;">
<?php
// Verifica se há mensagens
if (!empty($mensagens)) {
//recarrega($conexao,$numeroCliente,$ultimoIdMensagem);
foreach ($mensagens as $mensagem) {
// Determina o nome e a imagem do remetente
$nome = ($mensagem['wa_action'] === 'receive') ? $mensagem['wa_name'] : 'Você';
$imagem = ($mensagem['wa_action'] === 'receive') ? '../whatsapp/imagens/user-solid1.png' : '../whatsapp/imagens/logo_crm.png'; // Caminho da imagem, pode ser dinâmico
// Determina o alinhamento (esquerda ou direita) dependendo de quem enviou
$align = ($mensagem['wa_action'] === 'receive') ? 'left' : 'right';
// Cria o balão de mensagem
echo createMessage($nome, $mensagem['wa_body'], $mensagem['wa_timestamp'], $imagem, $align);
//SE A MENSAGEM NÃO TIVER USUÁRIO ID_wa_user_msg, ele define ID_wa_user_msg OK
if($mensagem['ID_wa_user_msg']==NULL){
alteraVincMsgUser($conexao, $mensagem['ID_wa_msg'], $ID_user);
}
}
echo "<a id='last-message'></a>"; // Âncora para rolar até a última mensagem
} else {
echo "<p>Nenhuma mensagem encontrada para este número.</p>";
}
?>
<a id="last-message"></a> <!-- Âncora para rolar até aqui -->
</div> <!--/.direct-chat-messages-->
And this is the code to send a message to the client:
<!-- ------------------------------------------------- Envia mensagem quando clica em "Send" -->
<?php
if (($_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_POST['message'])){
//if (!empty($_POST['message'])) {
$ultimaMensagem = $_POST['message']; // Recupera a mensagem
//sendUser($conexao, $ultimaMensagem); // Envia a mensagem para o banco de dados
sendUser($conexao, $ultimaMensagem, NULL, 1, 2, 1);
// Retorna uma resposta de sucesso
echo json_encode(['status' => 'success', 'message' => 'Mensagem enviada com sucesso!']);
//} else {/*
// Retorna uma resposta de erro
/*echo json_encode(['status' => 'error', 'message' => 'O campo de mensagem não pode estar vazio!']);*/
//}
exit; // Encerra o script após retornar a resposta
}
?>
<!-- Formulário -->
<form id="messageForm" method="POST">
<div class='row'>
<div class='col-md-12'>
<div class='form-group'>
<!--<label>11 Digite a MENSAGEM ...</label>-->
<div class="input-group">
<div class='input-group-prepend'>
<span class='input-group-text'><i class='fas fa-keyboard'></i></span>
</div>
<input type="text" class='form-control' id="messageInput" name="message" placeholder="Digite a MENSAGEM ..." class="form-control" required>
<span class="input-group-append">
<button type="submit" name="send" class="btn btn-primary">ENVIAR</button>
</span>
<!--<div class='col-md-4' style="padding-left: 0px; text-align: left;">
<button type='submit' class='btn btn-info float-right' id='cadastrar'>ENVIAR</button>
</div>-->
</div>
</div>
</div>
</div>
</form>
I would like to know if there is a way for me to reload the page every time I receive new data in my database. Or any other way to reload this form/conversation when I receive new data in the database.
Edit: I researched websockets and found Ratched, the best for PHP. But I also found out that you need a VPS server, but the source for this information is not reliable. I understand how Ratched works, but I don't want to start implementing it only to find out that it doesn't work for me. I currently use Hostinger as my server. Since I'm relatively new to programming, I would like more detailed guidance on how to make this work.