Real-Time Web: AJAX Polling and Long Connections
The web is no longer just static pages. Jesse James Garrett coined the term "AJAX" earlier this year, and the world is going crazy. But the biggest challenge remains: the server cannot "push" data to the client. The browser must always initiate the request. How do we build something like a real-time stock ticker or a chat room?
The Simple Polling Strategy
The most basic approach is to just ask the server for updates every few seconds.
function pollServer() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "/get-updates.php", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
updateUI(xhr.responseText);
// Wait 5 seconds and poll again
setTimeout(pollServer, 5000);
}
};
xhr.send(null);
}
This works, but it's incredibly inefficient. 99% of those requests will return "no new data," wasting bandwidth and server resources.
The "Long Polling" Hack
To get closer to real-time, we can use a technique often called "Comet" or "Long Polling." The client makes a request, and the server holds the connection open until it has something to say.
// On the server (PHP example)
while (true) {
$data = check_for_new_messages();
if ($data) {
echo json_encode($data);
break;
}
usleep(500000); // Sleep for 0.5s to save CPU
}
When the client receives the response, it immediately opens a new request. This makes the app feel instant, but it requires a specialized server setup. If you're using Apache's mod_php, each open connection consumes a whole process, which will kill your server at even moderate scale.
We're still in the wild west of "web applications," but AJAX has finally broken the "click-wait-refresh" cycle.
Aunimeda builds modern web frontends - from single-page applications to complex multi-locale sites.
Contact us to discuss your frontend project. See also: Web Development, Corporate Website Development