I prepare the simplest way of AJAX long polling (realtime) in vanilla JavaScript, without any libraries like jQuery...
The code works based on timestamp of data.txt read by PHP file server.php (that's all).
function realtime(timestamp) {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'server.php' + (typeof timestamp !== 'undefined' ? '?timestamp=' + timestamp : ''), true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var result = JSON.parse(xhr.responseText);
document.getElementById('response').innerHTML = result.content;
realtime(result.timestamp);
}
};
xhr.send();
}
realtime();
Now, I would like to know how to prepare similar example in websocket (without any libraries, just clean JS/PHP).
It is possible?
Websocket is a different protocol than HTTP (it uses the HTTP upgrade mechanism). So you'll have to adapt your webserver AND any reverse proxy etc. to handle websocket connections.