Html Form not submitting data to server - html

I'm trying to submit Customer data to the server for processing. I'm using an HTML form. But every time I press submit the server doesn't receive any data in the request.
<form data-customer-information-form="true" autocomplete="on" method="POST" action="addticket/submit" name="ticketForm" id="ticketform" accept-charset="UTF-8">
<p>
<label for="customerFirstName">First Name:</label></br>
<input type="text" name="customerFirstName" id="customerFirstName" placeholder="first name" pattern="[A-Za-z]+" tabindex="0">
</p>
<p>
<label for="customerLastName">Last Name:</label></br>
<input type="text" name="customerLastName" id="customerLastName" placeholder="last name" tabindex="0">
</p>
<p>
<label for="phoneNumber">Phone:</label></br>
<input type="tel" id="phone" maxlength="12" name="phoneNumber" placeholder="phone" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" tabindex="0">
</p>
<p>
<label for="email">Email:</label></br>
<input type="email" name="email" id="email" placeholder="email">
</p>
<p>
<label for="service">Computer/Service Name:</label></br>
<input type="text" name="service" placeholder="computer model or service">
</p>
<p>
<label for="description">Anything else we need to know:</label></br>
<textarea type="text" maxlength="200" name="description" id="description" placeholder="What's gone wrong?"></textarea>
</p>
<input type="submit" name="submit" value="Submit" id="submit">
</form>
const router = require('express').Router();
const fs = require('fs');
var path = require('path');
const customer = require("../models/customer");
router.get('/', function(req, res) {
req.session.cookie
res.sendFile(path.join(__dirname + "/pages/ticket.html"));
});
router.post('/submit', (req, res) => {
console.log(req.body)
})
module.exports = router;
The request headers all look good telling the server that is a form. But it doesn't have the data. req.body is undefined basically.

Express.js will only populate the body property of a request object if suitable body parsing middleware is used. You aren't using any.
By default, a form will encode form data in the URL encoded format, so you should use that middleware.
const express = require('express');
router.use(express.urlencoded())

Related

Node.JS - Express request returns undefined when when submitting a post request from a form

When I try to get an HTML form from using Node.JS/Express it seems to return a undefined value as the req.body returns an empty object.
Node
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const port = '3000'
app.use(bodyParser.urlencoded({ extended: true}))
app.use(bodyParser.json());
app.use(express.static('public'))
app.get('/',function(req, res) {
res.sendFile( __dirname + '/signup.html')
});
app.post('/', function(req, res) {
const FirstName = req.body.firstName
const LastName = req.body.lastName
console.log(FirstName)
console.log(LastName)
});
app.listen(port, function(err) {
if (err) console.log(err)
console.log('Local port started at', port)
});
HTML
<form action="/" method="post"\>
<label for="firstName"\>First Name\</label\>
<input class="form-grid__item--field" type="text" id="firstName" placeholder="First Name"\>
<label for="lastName">Last Name</label>
<input class="form-grid__item--field" type="text" id="lastName" placeholder="Last Name">
<label for="subscriberEmail">Email</label>
<input class="form-grid__item--field" type="text" id="subscriberEmail" placeholder="Email">
<input type="submit" class="form__button" value="Sign Me Up!">
</form>
Reformatted the code several times. Looked into the html form to ensure the action and methods where in place. When over body parser documentation to try and get more context but nothing.
The id field inside input label is used for referencing the element in the DOM.
In order to pass the input as a field in the request you must give it attribute name
<input class="form-grid__item--field" type="text" id="subscriberEmail" name="subscriberEmail" placeholder="Email">
The req.body searches for the name attribute in your form. Add the name attribute and then access them via req.body.theNameOfTheAttribute
<form action="/" method="post"\>
<label for="firstName"\>First Name\</label\>
<input class="form-grid__item--field" type="text" id="firstName" placeholder="First Name"\>
<label for="lastName">Last Name</label>
<input class="form-grid__item--field" type="text" id="lastName" placeholder="Last Name">
<label for="subscriberEmail">Email</label>
<input class="form-grid__item--field" type="text" id="subscriberEmail" placeholder="Email">
<input type="submit" class="form__button" value="Sign Me Up!">
</form>

nodejs not listening to post requests and returns error 505

i'm just a begineer to nodejs and I am trying to complete this project and i have been stuck since almost 2 days and i'm unable to figure this out.
it seems nodejs is not listening to POST requests, I am console logging but it instead returns 405 error page.
Here's the code:
import express, { urlencoded } from 'express';
import path, {dirname} from 'path';
import { fileURLToPath } from 'url';
import mysql from 'mysql';
const app = express();
app.use(express.json());
app.use(urlencoded({ extended : true}));
app.use(express.static('public'));
// const __dirname = path.dirname(fileURLToPath(import.meta.url));
app.post('/' , (req, res)=>{
console.log(req.body);
// res.sendFile(path.join(__dirname ,'/public/index.html'));
});
app.listen(5501, ()=>{
console.log('Server is running at port 5501')
})
<form action="/" method="post" id="cont-form">
<h1 class="contact-h1">Contact us</h1>
<div>
<input type="text" name="name" placeholder="Your name" autocomplete="off">
</div>
<div>
<input type="text" name="subject" placeholder="Subject" autocomplete="off">
</div>
<div>
<input type="email" name="email" placeholder="Email" autocomplete="off">
</div>
<div>
<label for="name">
<textarea name="message" placeholder="Type your message" cols="30" rows="10"></textarea>
</label>
</div>
<input type="submit" name="submit" id="submit-ms" value="Send message">
</form>
<div class="buy">
<div class="quantity">
<i class="fa-solid fa-xmark close-buy"></i>
Select Quantity
</div>
<form action='/buy' method="post" >
<div class="inputs">
<div class="buy-input-div" style="margin-top:16px">
<box-icon name='user'></box-icon>
<input type="text" class="buy-input" name="title" id="title-text"></div>
<div class="buy-input-div" >
<box-icon name='user'></box-icon>
<input type="text" class="buy-input" placeholder="Full Name" name="fullname" id="person-name"></div>
<div class="buy-input-div">
<box-icon name='phone'></box-icon>
<input type="text" class="buy-input" placeholder="Phone Number" name="phone" id="phone"></div>
<div class="buy-input-div">
<box-icon name='envelope'></box-icon>
<input type="text" class="buy-input" placeholder="Email" name="email" id=""></div>
<div class="buy-input-div">
<box-icon name='building'></box-icon>
<input type="text" class="buy-input" placeholder="Address" name="address" id=""></div>
<div class="buy-input-div">
<box-icon name='plus'></box-icon>
<input type="number" class="buy-input" placeholder="Quantity" name="quantity" id="">
</div>
<button class="buy-btn">Buy</button>
</div>
</form>
</div>
my file structure:
--root
--node_modules
--public
--index.html
--AdminPanel.html
--styles.css
--script.js
--index.js
--package-lock.json
--package.json
This is how it looks like:
You've got only one endpoint using POST method. Browsers sends only GET requests. (405 means Method not allowed).
You need to define a GET endpoint which will serve the html code. And in browser you have to access that endpoint. When you'll press the submit from you server html it will send a POST request.
Edited: If you access that file statically (opening the html file in a browser) then you need to specify in action property of form tag the full address, since / will simply try the location on your machine

Sending a form on webhook + on a confirmation page

Here is the problem I have:
When validating my form I would like to :
1- Send the form information to a Webhook (to process the information) I would like it to be invisible for the user
2- Redirect the user to a confirmation page (or display a confirmation message on the form)
Here is my current form that only sends the info to the webhook:
<form method="post" action="https://hooks.zapier.com/hooks/catch/12195186/bzjhk97/">
<input id="prenom" type="text" name="first_name" placeholder="Votre prénom" required="required" />
<input id="email" type="email" name="email" placeholder="Votre adresse e-mail" required="required" />
<button id="submit" type="submit" class="btn">RECEVOIR LE KIT COMPLET</button>
I don't know if it's adjustable with Javascript or just HTML...
Thanks for your help :)
You can change your button type to "button" and then add a handler to that button to POST the data. In the example below I modified your code to do that and use fetch to POST the data to the endpoint.
Inside the ".then" part is the callback (this does not get execited until you receive the response from the fetch). This is where you would display the dialog to the user or redirect them to another page.
<form method="post" action="https://hooks.zapier.com/hooks/catch/12195186/bzjhk97/">
<input id="prenom" type="text" name="first_name" id="first_name" placeholder="Votre prénom" required="required" />
<input id="email" type="email" name="email" id="email" placeholder="Votre adresse e-mail" required="required" />
<button id="submit" type="button" class="btn" id="btn">RECEVOIR LE KIT COMPLET</button>
</form>
<script>
const getButton = document.getElementById('btn');
const getFirstName = document.getElementById('first_name');
const getEmail = document.getElementById('email');
fetch('https://hooks.zapier.com/hooks/catch/12195186/bzjhk97/', {
method: 'POST',
body: new URLSearchParams({
first_name: getFirstName.value,
email: email.value
})
})
.then(response => {
// Do stuff with the response
});

Suggest User name based on full name and date of birth

HTML -
<form action="/addUser" method="post">
<div class="Fields hideme">
<label class="form__fields">Full Name :<span class="star"> * </span></label>
<input class="input" type="text" name="full_name" placeholder="Enter your name" required><br/>
</div>
<div class="Fields hideme">
<label class="form__fields">Address line 1:<span class="star"> * </span></label>
<input class="input" type="text" name="address_line_1" placeholder="Address line 1" required><br/>
</div>
<div class="Fields hideme">
<label class="form__fields">DOB :<span class="star"> * </span></label>
<input class="input" type="date" name="DOB" placeholder="DOB" required><br/>
</div>
</div>
<div class="Fields hideme">
<label class="form__fields">Email :<span class="star"> * </span></label>
<input class="input" type="email" name="email" placeholder="Enter your E-mail" required><br/>
</div>
<div class="Fields hideme">
<input class="Submit_button" type="submit" value="Submit">
</div>
</form>
I am saving this user using node.js
JS -
var nameSchema = new mongoose.Schema({
full_Name: String,
.
.
email: String
});
var User = mongoose.model("User", nameSchema);
const publicPath = path.join(__dirname,'/');
app.use(express.static(publicPath));
app.post("/addUser", (req, res) => {
var myData = new User(req.body);
myData.save()
.then(item => {
res.send("User saved to database");
})
.catch(err => {
res.status(400).send("Unable to save to database");
});
});
I have a html form in which I am asking a user to enter info like Name, DOB, address, Email and I have to suggest User Names based on these inputs to the user.
Please tell me how to send back a suggested userName based on the inputs by the user(full name, DOB, address).
I wanted to write in the comments but I don't have enough reputations.
So I will write it as an answer.
I personally recommend you to use heroku or digitalocean because they are very good for nodejs.
mlab is the best for your DB if you are using MongoDB.
And you can google it or search on youtube there are tons of information.
I hope you will find the answer.

HTML form not sending data in Express

I have the following form in HTML:
<form method="post" id="registration-form" action="/register">
<div class="form-group">
<label for="UsernameRegistration">Username:</label>
<input type="text" class="form-control" id="UsernameRegistration">
</div>
<div class="form-group">
<label for="PasswordRegistration">Password:</label>
<input type="password" class="form-control" id="PasswordRegistration">
</div>
<div class="form-group">
<label for="ConfirmPasswordRegistration">Confirm Password:</label>
<input type="password" class="form-control" id="ConfirmPasswordRegistration">
</div>
<input type="submit" class="form-control" />
</form>
The /register endpoints looks like the following:
router.post('/register', function(req, res, next) {
console.log(req);
});
In req.query and req.body, there is no data. What am I doing wrong?
<input type="password" class="form-control" id="PasswordRegistration">
Here the attribute name is not specified.
It should be like
<input type="password" name="password" class="form-control" id="PasswordRegistration">
You haven't provided name attribute for input elements .
I you provide name attribute to element eg:
<form method="post" id="registration-form" action="/register">
<div class="form-group">
<label for="UsernameRegistration">Username:</label>
<input name="username" type="text" class="form-control" id="UsernameRegistration">
</div>
<div class="form-group">
<label for="PasswordRegistration">Password:</label>
<input name="password" type="password" class="form-control" id="PasswordRegistration">
</div>
<div class="form-group">
<label for="ConfirmPasswordRegistration">Confirm Password:</label>
<input name="confpass" type="password" class="form-control" id="ConfirmPasswordRegistration">
</div>
<input type="submit" class="form-control" />
</form>
router.post("/registration", (req, res) => {
var username = req.params.username;
var pass = req.params.password;
var confpass = req.params.confpass;
})
You will get data in req.params object.
I think you are missing these two things :-
1.Have you added body parser in our app ?? (Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser)
var app = require('express')();
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
Missing name attribute in your form elements