Welcome to a tutorial on how to create a simple booking system with Javascript and NodeJS – Yes, this is pretty much a pure HTML, CSS, and Javascript project. Read on!
TABLE OF CONTENTS
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
EXAMPLE CODE DOWNLOAD
Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
JAVASCRIPT BOOKING
All right, let us now get into more details on how the booking system works. Not going to explain line-by-line, but here’s a quick walk-through.
QUICK SETUP
Install NodeJS if you have not already done so, run npm i express nodemailer body-parser multer
to install the required modules.
STEP 1) BOOKING FORM
1A) THE HTML
<!-- (A) BOOKING FORM -->
<form id="bookForm" onsubmit="return book();">
<label for="name">Name</label>
<input type="text" name="name" required>
<label for="email">Email</label>
<input type="email" name="email" required>
<label for="date">Date</label>
<input type="date" name="date" required>
<input type="submit" value="Go!" disabled id="bookGo">
</form>
This should be self-explanatory. Just a simple HTML form with 3 fields – The name, email, and reservation date.
1B) THE JAVASCRIPT
function book () {
// (A) PREVENT MULTIPLE SUBMIT
document.getElementById("bookGo").disabled = true;
// (B) COLLECT FORM DATA
let data = new FormData(document.getElementById("bookForm"));
// (C) SEND!
fetch("/book", { method:"POST", body:data })
.then(res => {
if (res.status==200) { location.href = "/thankyou"; }
else { alert("Opps an error has occured."); }
})
.catch(err => {
console.error(err);
alert("Opps an error has occured.");
});
return false;
}
// (D) INIT
window.onload = () => {
// (D1) MIN SELECTABLE DATE IS TODAY
let datepick = document.getElementsByName("date")[0];
datepick.min = new Date().toISOString().split("T")[0];
// (D2) ENABLE FORM
document.getElementById("bookGo").disabled = false;
};
A little bit of Javascript here to better manage the form:
- (D1) Restrict the earliest reservation date to today on window load – Go ahead and set your own minimum/maximum date rules here.
- (D2) Enable the submit button when the page is properly loaded.
- (A To C) Yep, we will be submitting the form via AJAX (no page reload). Redirect the user to the “thank you” page on success.
STEP 2) THANK YOU PAGE
<h1>THANK YOU</h1>
<p>We have received your booking request.</p>
Well, the “mandatory thank you page”.
STEP 3) NODE SERVER
// (A) LOAD REQUIRED MODULES
// npm i express nodemailer body-parser multer
const express = require("express"),
bodyParser = require("body-parser"),
nodemailer = require("nodemailer"),
multer = require("multer"),
path = require("path");
// (B) SETTINGS - CHANGE TO YOUR OWN!
// https://nodemailer.com/
const portHTTP = 80,
mailSet = {
port : 25,
host : "localhost",
/* auth: {
user: EMAIL/USER,
pass: PASSWORD
},*/
tls: { rejectUnauthorized: false }
},
mailFrom = "sys@mail.com",
mailAdmin = "manager@mail.com",
mailSubject = "Reservation",
mailTxt = "Booking request received.";
// (C) NODE MAILER & EXPRESS SERVER
const app = express(),
forms = multer();
app.use("/assets", express.static(path.join(__dirname, "assets")));
app.use(forms.array());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const mailtransport = nodemailer.createTransport(mailSet);
// (D) EXPRESS HANDLERS
// (D1) HOME PAGE - BOOKING FORM
app.get("/", (req, res) => res.sendFile(path.join(__dirname, "1-booking.html")));
// (D2) SEND BOOKING REQUEST VIA EMAIL
app.post("/book", (req, res) => {
// (D2-1) MAIL MESSAGE
let msg = mailTxt + "<br>";
for (const [k, v] of Object.entries(req.body)) { msg += `${k} : ${v}<br>`; }
// (D2-2) SEND
mailtransport.sendMail({
from: mailFrom,
to: mailAdmin,
subject: mailSubject,
html: `<p>${msg}</p>`
}, (error, info) => {
if (error) {
console.log(error);
res.sendStatus(500);
} else {
console.log(req.body);
res.sendStatus(200);
}
});
});
// (D3) THANK YOU
app.get("/thankyou", (req, res) => res.sendFile(path.join(__dirname, "2-thank-you.html")));
// (E) START!
app.listen(portHTTP);
The Node server script is probably the most intimidating, but keep calm and walk through part-by-part:
- Load all the required modules.
- A bunch of settings – Remember to change the email to your own.
- Initialize the Express HTTP server and mail transporter.
- Pages to serve in the HTTP server.
http://site.com/
The main page, booking form.http://site.com/book/
Where we POST and process the booking form, this will send an email to your specified email address.http://site.com/thankyou/
The thank-you page.
- Start the server.
Yep, that’s about it. It may look confusing, but it is actually just long-winded.
EXTRAS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
HOW DO I PUT THIS ONTO A LIVE SERVER?
There are so many different services and hosting companies that support NodeJS – Amazon Web Services (AWS), Google Cloud, Microsoft Azure, Kamatera, A2 Hosting, DigitalOcean, Heroku, etc… Just do a search for “NodeJS hosting” on the Internet and there are a ton more.
LOCAL SMTP MAIL TESTING
You guys on Linux/Mac should be fine so long as sendmail
is in place. For Windows users, one of the easier ways is to just install Papercut SMTP for easy testing.
LINKS & REFERENCES
- Node Mailer
- PHP Reservation System – Code Boxx
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
thank you brother.