1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { Hono } from "npm:hono";
const app = new Hono();
// Endpoint to catch and log the submitted name
app.post("/submit-name", async (c) => {
const data = await c.req.parseBody();
console.log('data:', data, Object.keys(data));
console.log("Received name:", data.name);
return c.json({ message: `Received name: ${data.name}` });
});
// Serve the HTML page with Alpine.js
app.get("/", (c) => {
const html = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Reactive Form with Alpine.js</title>
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
<script defer src="https://unpkg.com/htmx.org"></script>
<script>
document.addEventListener('alpine:init', () => {
Alpine.data('utils', () => ({
name: '',
output: null,
init() {
// if you don't use an arrow function (this) will refer to document, not alpine
document.addEventListener('htmx:afterRequest', (event) => this.updateOutput(event));
},
updateOutput(event) {
this.output = JSON.parse(event.detail.xhr.response);
if (event.detail.target.id == 'output') {
console.log('#output received a swap', event.detail.xhr.response);
}
},
}))
});
// document.addEventListener('DOMContentLoaded', () => {
// htmx.logAll();
// });
</script>
</head>
<body>
<div x-data="utils">
<form @submit.prevent hx-post="/submit-name" hx-target="#output">
<label for="name">Name:</label>
<input type="text" id="name" name="name" x-model="name" placeholder="Enter your name">
<button type="submit">Submit</button>
</form>
<div class="htmx-container" style="margin-top:16px" >
<span x-show="output">htmx response swap — set this to hidden to use the data</span>
<div id="output" x-text="output?.message"></div>
</div>
<div x-show="output" style="margin-top:16px" class="alpine-container">
Output data stored in alpine: <pre x-text="JSON.stringify(output, null, 2)"></pre>
</div>
</div>
</body>
</html>
`;
return c.html(html);
});
export default app.fetch;