Continually refresh game data using AJAX I've been working with JavaScript and AJAX a lot in the past, and now I'm moving towards the backend and working with databases more. I want to update my game data in as close to real time as possible in JavaScript.

Here is what I have been doing to update the data as frequently as possible (I simplified it):

function updateData() {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.ontimeout = function (e) {
            // XMLHttpRequest timed out. Try sending another request
            updateData();
        };
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 &amp;&amp; this.status == 200) {
                // only keep the data after the leading { (in case errors are outputted) (SHOULD NOT HAPPEN)
                var data = this.responseText.slice(this.responseText.indexOf('{'));
                try {
                    data = JSON.parse(data); // we're expecting JSON data -- make this an object for us
                } catch (error) {
                    console.error("Error parsing data");
                }
                // handle data...
                // and repeat:
                updateData();
            }
        };
        xmlhttp.open("GET", "data_getter.php", true); // "?t=" + getTime() to endure that the data is not cached
        xmlhttp.send();
}
updateData();


I call the function updateData() once and then each time the previous request is received, the function gets ran again.

I am wondering, is there a better way to continually refresh data (or make the data on the game website as close to realtime as possible) than to send an AJAX request every time the previous one is received? This method means that there will be a delay of the time it takes for the server to load, but that isn't too much.

Is this the best practice? Or can you somehow open a connection to a PHP script that communicates with the server in realtime and not close the connection for the duration of the game?
Reviewing your function

Looking at updateData() shows:


(reading signature only) there's no return value. So it does something inside, potentially modifying state (outside your function scope)
(reading body) it has two responsibilities: (1) retrieve data from server via http query; (2) actual update of variable data by assigning retrieved data to it.
it calls itself in two conditional branches. In fact it's a recursive function.


Improve:

(1) The function could return retrieved data. This would make it a pure function representing query part (of CQRS).

(2) This violates CQRS. You could improve by separating query (http data retrieval) from command (updating state: assigning a new value to a variable).

(3) recursive calls of same HTTP GET request in order to keep state up-to-date  are conceptually called long-polling. This polling is usually implemented as consecutive GET requests between intervals using a timer. To reduce unnecessary updates, the polling makes advantage of HEAD requests using modifiedSince header and E-tags (both telling if server has updated data or no change since last fetch).
A resource-friendly alternative to long-polling is the use of web-socket protocol.

Web-sockets

An event-based communication between server and client via a dedicated socket-connection. This connection is opened once allowing bi-directional asynchronous text-messages. Thus the server can send an update-notification (either including updated data or to allow the client to retrieve data in a separate GET request).

There are web-socket libraries for both JavaScipt (client) and PHP (server).