Adding Data (reactive)
Goal: Let visitors add new Todos through an HTML form. You'll meet #partial public
, #param
, and #insert
—the minimum write path. hx-post
handles the submission.
Estimated time: 15 minutes.
1 What we're building
- Before:
/todos
shows a read‑only list (Part 1). - After: Typing in an input box creates a row in the
todos
table and it appears instantly.
2 Extend templates/todos.pageql
Add the lines after the <h1>...</h1>
and append a new public partial at the top of the file.
<!-- Add the following lines after <h1>Todos</h1> --> <input name="text" placeholder="What needs to be done?" autofocus autocomplete="off" hx-post="/todos/add" hx-trigger="keyup[key=='Enter']" hx-on:htmx:after-on-load="this.value=''">
<input name="text" placeholder="What needs to be done?" autofocus autocomplete="off" hx-post="/todos/add" hx-trigger="keyup[key=='Enter']" hx-on:htmx:after-on-load="this.value=''">
<!-- Add this partial at the top of the file --> {{#partial POST add}} {{#param text required minlength=1}} {{#insert into todos(text, completed) values (:text, 0)}} {{/partial}}{{#partial POST add}} {{#param text required minlength=1}} {{#insert into todos(text, completed) values (:text, 0)}} {{/partial}}
Save the file—your dev server is still running from Part 1 and reloads the page automatically.
3 Walk‑through
Piece | Purpose |
---|---|
<input hx-post="/todos/add" …> |
Sends an AJAX POST to the add partial when you press Enter. |
#partial public add |
Turns a template block into an HTTP endpoint at /todos/add . |
#partial POST add |
Turns a template block into an HTTP endpoint at /todos/add . |
#param text required minlength=1 |
Validates and binds request parameters. Stops processing with a clear error if validation fails. |
#insert into |
Executes INSERT INTO todos … safely with bound params. |
3.1 Request cycle in 3 steps
- Browser: hx-post
/todos/add
⇢ body{text="learn PageQL"}
- Server: partial
add
validates → inserts → list updates automatically.
POST /todos/add → UI updates automatically
4 Try it out
- Open http://localhost:8000/todos
- Type "Feed the cat" → Enter.
- Your new item appears instantly without reloading.
- Add a blank item—notice how validation blocks it with an error page.
You can observe the incoming update messages in the browser’s network inspector under the WS tab.
(Validation errors return a plain‑text stack trace in dev mode; there's no production mode yet.)
5 Recap
- Public partials = endpoints. They keep GET pages slim by moving mutations out.
#insert
is SQL, not magic. Every column and param is explicit and bound.- hx-post triggers AJAX submissions and the list updates automatically.
- The dev server pushes changes over a WebSocket. Open the Network tab in your browser’s inspector and watch the WS frames appear.