Static HTML and server rendering → AJAX
1991 – today · 1999 – today
What changed
- Where the state lives
Static HTML and server rendering
On the server: the todo list is server data; the current filter is in the URL and in hidden form fields.
AJAX
On the server: the list is server data; the page keeps the last copy it received, and the filter.
- How the page is rendered
Static HTML and server rendering
The server writes the whole page as an HTML string for every request; the browser only displays it.
AJAX
The server sends data (JSON), not HTML; the page builds the list items with
document.createElement.- What happens on a change
Static HTML and server rendering
Every action is a request: a form POST or a link GET, answered by a complete new page.
AJAX
Each change is a background request; its callback replaces the page's copy of the list and redraws only the list, the counter and the filter buttons.
- How the code is organised
Static HTML and server rendering
One server program that routes requests and renders pages. No JavaScript is needed in the browser.
AJAX
A page script with a request helper and handlers attached in
window.onload, talking to a server API that answers JSON.
Why it changed
What hurt in each era along the way, and the era that came next.
Static HTML and server rendering→Dynamic HTML and the browser wars
Every change, even ticking one checkbox, is a round trip to the server and a new page: the screen flashes, the scroll position and anything half-typed are lost, and the user waits for the network each time. Pages could not react to the user on their own. JavaScript (1995) and Dynamic HTML let the page change itself in the browser.
Dynamic HTML and the browser wars→AJAX
The page could change itself, but it could not exchange data with the server without leaving: loading fresh data or saving a change still meant a form submission or a link and a whole new page, and everything kept in variables was gone after it. On top of that, every browser needed its own branch of the code. XMLHttpRequest and the AJAX approach let a script talk to the server in the background and update only the part of the page that changed.
The same app, side by side
The main file of each version. Both apps pass the same test: same markup, same behaviour, different ideas.
The apps run in sandboxes in your browser.
Static HTML and server rendering
plain browser APIs, no library
/server.js · 83 lines
// Static HTML era: the server builds every page; the browser shows it and sends forms back.
// In the 1990s this was a CGI script (often Perl, later PHP); here it is JavaScript.
// The "database" lives on the server, so the list survives every page load.
const todos = [
{ id: 1, title: "Read the docs", done: true },
{ id: 2, title: "Write the app", done: false },
];
let nextId = 3;
const FILTERS = { all: "All", active: "Active", done: "Done" };
// Text typed by users must be escaped before it goes into the HTML.
function escapeHtml(text) {
return String(text)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """);
}
function renderPage(filter) {
const shown = todos.filter((t) => filter === "all" || (filter === "done") === t.done);
const left = todos.filter((t) => !t.done).length;
// Every todo gets its own little form: toggling it is a POST to the server.
const items = shown
.map(
(t) => `
<li${t.done ? ' class="done"' : ""}>
<form method="post" action="/todos/${t.id}/toggle">
<input type="hidden" name="filter" value="${filter}">
<button type="submit" data-toggle>${t.done ? "Undo" : "Done"}</button>
</form>
<span class="title">${escapeHtml(t.title)}</span>
</li>`,
)
.join("");
// Filters are plain links: choosing one loads a new page.
const links = Object.entries(FILTERS)
.map(
([name, label]) =>
`<a href="/?filter=${name}" data-filter="${name}"${name === filter ? ' class="selected"' : ""}>${label}</a>`,
)
.join(" ");
return `
<main class="todo-app">
<h1>Todos</h1>
<form id="todo-form" method="post" action="/todos">
<input type="hidden" name="filter" value="${filter}">
<input id="new-todo" name="title" placeholder="What needs doing?" autocomplete="off" aria-label="New todo">
<button id="add" type="submit">Add</button>
</form>
<ul id="todo-list">${items}
</ul>
<div class="footer">
<span id="todo-count">${left} left</span>
<div class="filters">${links}</div>
</div>
</main>`;
}
// One request in, one whole page out. The answer to a POST is the new page itself.
export function handle({ method, path, query, form }) {
const asked = form?.filter ?? query.filter;
const filter = Object.hasOwn(FILTERS, asked ?? "") ? asked : "all";
if (method === "POST" && path === "/todos") {
const title = (form.title ?? "").trim();
if (title) todos.push({ id: nextId++, title, done: false });
}
const toggle = path.match(/^\/todos\/(\d+)\/toggle$/);
if (method === "POST" && toggle) {
const todo = todos.find((t) => t.id === Number(toggle[1]));
if (todo) todo.done = !todo.done;
}
if (path === "/" || method === "POST") return { status: 200, body: renderPage(filter) };
return { status: 404, body: "<h1>Not found</h1>" };
}AJAX
plain browser APIs, no library
/src/main.js · 97 lines
// AJAX era: the page talks to the server in the background with XMLHttpRequest and
// redraws only the list. The page itself is never loaded again.
// The list belongs to the server; the page keeps the last copy it received.
var todos = [];
var filter = "all";
// Every request goes the same way: open, send, then wait until readyState is 4 (done).
function request(method, url, body, callback) {
var xhr = new XMLHttpRequest();
// true = asynchronous: the page stays usable while the request travels.
xhr.open(method, url, true);
if (body) xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
callback(JSON.parse(xhr.responseText));
}
};
xhr.send(body);
}
// Every answer is the whole list as JSON: keep it and redraw.
function show(list) {
todos = list;
render();
}
// One call per todo gives each handler its own todo. A handler created inside render()'s
// for loop would close over the loop's single var and see its value from the end of the loop.
function makeItem(todo) {
var li = document.createElement("li");
var label = document.createElement("label");
var box = document.createElement("input");
var title = document.createElement("span");
box.type = "checkbox";
box.checked = todo.done;
box.setAttribute("data-toggle", "");
box.onclick = function () {
request("POST", "/todos/" + todo.id + "/toggle", null, show);
};
// A text node: what the user typed never becomes HTML.
title.className = "title";
title.appendChild(document.createTextNode(todo.title));
label.appendChild(box);
label.appendChild(document.createTextNode(" "));
label.appendChild(title);
li.appendChild(label);
if (todo.done) li.className = "done";
return li;
}
// Only the list, the counter and the filter buttons change; the rest of the page stays.
function render() {
var list = document.getElementById("todo-list");
var buttons = document.getElementById("filters").getElementsByTagName("button");
var left = 0;
var i;
list.innerHTML = "";
for (i = 0; i < todos.length; i++) {
if (!todos[i].done) left++;
if (filter === "all" || (filter === "done") === todos[i].done) {
list.appendChild(makeItem(todos[i]));
}
}
document.getElementById("todo-count").innerHTML = left + " left";
for (i = 0; i < buttons.length; i++) {
buttons[i].className = buttons[i].getAttribute("data-filter") === filter ? "selected" : "";
}
}
// Handlers are attached from the script when the page has loaded, not written into the HTML.
window.onload = function () {
var field = document.getElementById("new-todo");
var buttons = document.getElementById("filters").getElementsByTagName("button");
var i;
document.getElementById("todo-form").onsubmit = function () {
var title = field.value.replace(/^\s+|\s+$/g, "");
if (title !== "") {
request("POST", "/todos", "title=" + encodeURIComponent(title), show);
field.value = "";
}
// false cancels the normal submission: no new page, the request runs in the background.
return false;
};
for (i = 0; i < buttons.length; i++) {
// Inside the handler, this is the button that was clicked.
buttons[i].onclick = function () {
filter = this.getAttribute("data-filter");
render();
};
}
// The page arrives without the list; the first request fetches it.
request("GET", "/todos", null, show);
};