Introduction
There are two key points to consider:
- When performing an action that requires server-side recording
- When passively observing updates on the webpage without taking any action (such as changes in vote indicators or notifications like "post has been revised, click to load," or "question closed, no more answers accepted")
Actions Requiring Server Recording (e.g., voting)
In such cases, JavaScript code sends ajax requests to the server. The server processes these requests independently using various technologies of your choice. When a user clicks on a vote button, the JavaScript code immediately updates the visual display and subsequently sends an ajax request to record the vote on the server (resulting in instant feedback). If there is a problem with the request processing (e.g., HTTP error or server rejecting the vote), an error message is displayed, and the display reverts back to its original state.
For instance, Stack Exchange utilizes the jQuery library for their JavaScript functionalities. Here's an example of how simple an ajax call can be made using jQuery:
$.ajax({
url: "/path/to/server/resource",
method: "POST",
data: {action: "voteup"},
success: function(data) {
// Execute actions based on successful response from server
},
error: function(jqXHR, textStatus, errorThrown) {
// Handle errors that occur during the process
}
});
The server's response corresponds to the POST operation accordingly.
Although jQuery is commonly used for ajax calls, other JavaScript libraries like YUI, Closure, Prototype, among others, also simplify ajax operations. While jQuery remains highly popular for web-based JavaScript tasks, alternatives exist.
Passive Observation
From an external perspective, it is likely that Stack Exchange employs various "comet" techniques (such as web sockets, long polling, hidden iframes, etc.) for passive updating.
Web sockets are probably the preferred option, allowing persistent bidirectional communication between clients and servers. Opening a question in Chrome with the Network tab reveals connections to
ws://sockets.ny.stackexchange.com/
, utilizing the web socket scheme outlined in RFC6455. This protocol facilitates seamless communication where servers can push data to clients.
While web sockets enjoy decent support, older techniques may still be utilized by SE for compatibility on browsers lacking web socket support.