Search code examples
javascriptxmlxmlhttprequest

XMLHttpRequest refresh only when a change on database is detected


My Ajax function is refreshing all the time, and I'd like it to just refresh when a change in a database is detected. Is there a way of doing this?

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);

Solution

  • 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 code examples, but there are plenty of examples on the interwebs showing how to do this, with either SSE or a websocket.