Simple Javascript Booking System (Step-By-Step Guide)

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!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TABLE OF CONTENTS

Download & Notes JS Booking Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

  • Install NodeJS if you have not already done so.
  • Download the code and unzip it to your project folder.
  • Open the command line, navigate to your project folder cd PATH/TO/YOUR/PROJECT
  • Run npm i express nodemailer body-parser multer to download all the required modules.
  • Done – run node 3-server.js and access http://localhost.
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

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.

 

STEP 1) BOOKING FORM

THE HTML

1-booking.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.

 

 

THE JAVASCRIPT

1-booking.html
 <!-- (B) A BIT OF JAVASCRIPT -->
<script>
// (B1) SEND BOOK
function book () {
  // PREVENT MULTIPLE SUBMIT
  document.getElementById("bookGo").disabled = true;
 
  // COLLECT FORM DATA
  let data = new FormData(document.getElementById("bookForm"));
 
  // 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) => { alert("Opps an error has occured."); });
  return false;
}
 
window.onload = () => {
  // (B2) MIN SELECTABLE DATE IS TODAY
  let datepick = document.getElementsByName("date")[0];
  datepick.min = new Date().toISOString().split("T")[0];
 
  // (B3) ENABLE FORM
  document.getElementById("bookGo").disabled = false;
};
</script>

A little bit of Javascript here to better manage the form:

  • (B2) Restrict the earliest reservation date to today on window load – Go ahead and set your own minimum/maximum date rules here.
  • (B3) Enable the submit button when the page is properly loaded.
  • (B1) 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

2-thank-you.html
<h1>THANK YOU</h1>
<p>We have received your booking request.</p>

Well, the “mandatory thank you page”.

 

 

STEP 3) NODE SERVER

3-server.js
// (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!
const portHTTP = 80,
      // https://nodemailer.com/
      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
const mailtransport = nodemailer.createTransport(mailSet);
 
// (D) EXPRESS SERVER
const app = express(),
      forms = multer();
app.use(forms.array());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
 
// (E) EXPRESS HANDLERS
// (E1) HOME PAGE - BOOKING FORM
app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname, "1-booking.html"));
});
 
// (E2) SEND BOOKING REQUEST VIA EMAIL
app.post("/book", (req, res) => {
  // MAIL MESSAGE
  let msg = mailTxt + "<br>";
  for (const [k, v] of Object.entries(req.body)) {
    msg += `${k} : ${v}<br>`;
  }
 
  // 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);
    }
  });
});
 
// (E3) THANK YOU
app.get("/thankyou", (req, res) => {
  res.sendFile(path.join(__dirname, "2-thank-you.html"));
});
 
// (F) START!
app.listen(portHTTP);

The Node server script is probably the most intimidating, but keep calm and walk through part-by-part:

  1. Load all the required modules.
  2. A bunch of settings – Remember to change the email to your own.
  3. Initialize the mail transporter.
  4. Initialize the Express HTTP server.
  5. 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.
  6. Start the server.

Yep, that’s about it. It may look confusing, but it is actually just long-winded.

 

 

USEFUL BITS & LINKS

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

 

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!

1 thought on “Simple Javascript Booking System (Step-By-Step Guide)”

Leave a Comment

Your email address will not be published. Required fields are marked *