Readme

Render form and save data

This val provides a web-based interface for collecting email addresses. It features a dual-functionality approach: when accessed via a web browser using a GET request, it serves an HTML form where users can submit their email address. If the script receives a POST request, it implies that the form has been submitted, and it proceeds to handle the incoming data.

Fork this val to customize it and use it on your account.

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
import { blob } from "https://esm.town/v/std/blob?v=11";
import { email } from "https://esm.town/v/std/email?v=9";
import { html } from "https://esm.town/v/stevekrouse/html?v=5";
export const renderFormAndSaveData = async (
req: Request,
): Promise<Response> => {
// A visit from a web browser? Serve a HTML page with a form
if (req.method === "GET") {
return html(`
<!DOCTYPE html>
<html>
<head>
<title>Email Form</title>
</head>
<body>
<form action="/" method="post">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
`);
}
// Otherwise, someone has submitted a form so let's handle that
const submittedEmailAddresses = (await blob.getJSON("submittedEmailAddresses")) ?? [];
const formData = await req.formData();
const emailAddress = formData.get("email");
if (submittedEmailAddresses.includes(emailAddress)) {
return new Response("you're already signed up!");
}
await email({
text: `${emailAddress} just signed up!`,
subject: "new sign up",
});
submittedEmailAddresses.push(emailAddress);
await blob.setJSON(
"submittedEmailAddresses",
submittedEmailAddresses,
);
return new Response("thanks! you're signed up!");
};
👆 This is a val. Vals are TypeScript snippets of code, written in the browser and run on our servers. Create scheduled functions, email yourself, and persist small pieces of data — all from the browser.