Part 4: Form Submission 101
Let's look at how we can apply htmx to a common web development scenario. Say we have a landing page that prompts the user to enter their contact information to a submission form.
The user enters their name and email address, and is redirected to a page showing a "thank you" message.
This is our app.rb
:
get '/' do
erb :'index'
end
post '/' do
redirect '/thank-you'
end
get '/thank-you' do
erb :"thank-you"
end
Here is markup for the index page:
<body class="viewport-centered">
<main>
<div class="focus">
<h1>Join waiting list</h1>
<p>Enter your name and email, and we will notify you when the program launches.</p>
<form action="/" method="post">
<ol class="user-fields">
<li>
<label for="name">Name <span class="req">*</span></label>
<input name="name" type="text" maxlength="255" tabindex="0" placeholder="Your Name" required>
</li>
<li>
<label for="email">Email <span class="req">*</span></label>
<input name="email" type="email" maxlength="255" tabindex="0" placeholder="name@email.com" spellcheck="false" required>
</li>
</ol>
<button type="submit">
<img src="/icons/thumb-up.svg" alt="Notify Me">
<span> Notify me! </span>
</button>
</form>
</div>
</main>
</body>
And the thank-you page:
<body class="viewport-centered text-centered">
<main>
<div class="check">✔</div>
<h2 class="no-margin">Thank you!</h2>
<p class="no-margin">We'll be in touch when we launch.</p>
</main>
</body>
This is as generic as it gets: one screen per action and zero personalization.
Wouldn't it be nicer if we showed a message that thanks the user personally, by their name? After all, they just submitted their name in the form, so it is available for us to use!
One way to do this is to fetch the name from the database — but this requires that you do save the user's details upon form submission. What if your use case doesn't call for that — maybe you simply want to send the user a quick email and then save their details later?
Also, what about just showing the "thank you" message in place, without navigating away from the landing page?
So here's our desired feature list:
- thank the user using his or her name, to make it more personal;
- display the thank-you message in-place, without navigating from the form submission page.
We will develop this functionality in three discrete steps:
- using the
GET
action with a redirect to a new URL - using the
POST
action while staying on the same URL - using htmx to achieve the above without a full page refresh.
Let's look at each one in turn.