top of page

Contact Forms in Node JS or Javascript and PHP

Updated: Nov 4, 2023

Clearing the confusion between forms and formdata


Dealing with forms without using JS

A form element with no “action” attribute will submit to the current route i.e. “http://127.0.0.1/index.html” which basically accomplishes absolutely nothing. So, you generally want to add action and method attributes to the form.


<form action=”<file or url to send the form to>” method=”<usually POST>”></form>


This will submit to the URI specified, which could be a local PHP handler or a NodeJS server endpoint.


EMAILING:
  • Typically, the ultimate goal is to deliver the form's input values collected from the user to an email alerting the client that someone wants to be contacted. To do this we need an email router.

  • If you don’t care about verifying form input fields, simply setting the action and method attributes will suffice in sending all form data to the URI specified in the action

Dealing with forms using JS

To verify the form data (OR DO ANYTHING ELSE BUT SUBMIT IT TO THE ACTION) we use a script.js, or probably validate.js.


First, we need to take control of the form and prevent it from being submitted:


const userSetupForm = document.querySelector("#setupForm");
userSetupForm.addEventListener("submit", (e) => {
 e.preventDefault();
}

Then we send the form data using ajax or fetch to either php-email-form.php

Two different email-handling libraries:

Submitting forms to a NodeJS endpoint

When submitting files you need to simply use a fetch request to send all of the form data as is, including any file upload inputs, using:

const form = new FormData(document.querySelector(“#form-ID”)) fetch(“http://customURL”, { method: “post”, body: form})

Note: this will send data as enctype=application/x-www-form-urlencoded by default.


multipart/form-data is what formidable wants to parse files out of, however not great if you just want to get a req.body object.


To get an object you have to make it from the form using:

const contactForm = document.querySelector(“#form-ID”)
const form = new FormData(contactForm) 
const formObject = Object.fromEntries(contactForm);

fetch(“http://customURL”, {
      method: "post",
      headers: {
        "Content-Type": "application/json",
      },
     body: JSON.stringify(formObject),
    })

Note: you cannot pass files this way, you may only pass along files to formidable using form, not formObject Then formidable can pull out the object on the server side using:



const form = formidable({ multiples: true });
     
form.parse(req, (err, fields, files) => {
        console.log(fields, files)
}



 
 
 

Comments


bottom of page