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.

« Part 1: Reading Data

1 What we're building

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

  1. Browser: hx-post /todos/add ⇢ body {text="learn PageQL"}
  2. Server: partial add validates → inserts → list updates automatically.

POST /todos/add  →  UI updates automatically

4 Try it out

  1. Open http://localhost:8000/todos
  2. Type "Feed the cat" → Enter.
  3. Your new item appears instantly without reloading.
  4. 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

« Back: Part 1: Hello Database Next: Part 3: Updating State