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 && 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 if there is 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?