XMLHttpRequest refresh only when a change on database is detected

So basically my ajax function is refreshing all the time, and I'd like that it just refreshes when a change on database is detected. Is there a way of doing this? Thank you

MY CODE:

function ajax(){
    var req = new XMLHttpRequest();
    req.onreadystatechange = function(){
        if (req.readyState == XMLHttpRequest.DONE && req.status == 200) {
                document.getElementById('chat').innerHTML = req.responseText;
        }
    }
    req.open('GET', 'chat.php', true);
    req.send();
    return false;

}

setInterval(function(){ajax();}, 100);

If you want to have server-push, you can use either Server Sent Events or a Websocket, instead of polling from the client with XMLHttpRequest.

You would have to detect a change in the database on the server side, and then push the change to the webpage using SSE or a websocket, or, alternatively, send a flag that there has been a change, and then pull the change from the webpage using XHR as you are doing now.

I don't know enough about your set-up to provide you with some code examples, but there are plenty of examples on the interwebs showing how to do this, with either SSE or a websocket.