I have a chat system but I want both the notifications and the messages to be updated immediately, I am using this code (setInterval) but it makes requests every 500 seconds so I think it is not very efficient, is there another way to do it?
setInterval(() => {
let xhr = new XMLHttpRequest();
xhr.open("POST", "INCLUDES/funciones/get-chat.php", true);
xhr.onload = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
let data = xhr.response;
chatBox.innerHTML = data;
if (!chatBox.classList.contains("active")) {
}
}
}
}
let formData = new FormData(form);
xhr.send(formData);
}, 500);
You should check WebSockets. You can lower the time between requests lowering the second parameter of setInterval but that would be bad. It would be a huge stress for your server that see a spike in the number of requests.
WebSocket, as the name said, open a socket, a permanent comunication channel between the server and client. This allows the server to send messages to the client.
The advantage is that if no message is ready for the client no traffic is sent and no new requests are made from the client to the server.
This is not the right place for a full chat code example because it's quite long. You can see Socket.io not the fastest but maybe the easiest library to work with WebScokets. Here you can find an example of a working chat (server and client) using Socket.IO