/    Sign up×
Community /Pin to ProfileBookmark

HTML Form posting several times with single button click

I am currently studying with Udemy but could not get an answer through their forums. I’m creating my own site to try and better understand mongoDB using mongoose, express, EJS. The site has multiple forms. When submitting form data with a post request I am attempting to insert a single record into a database but instead get 4 duplicate records inserted. When using console.log to check the object being sent it also appears 4 times, however I have tried to send it only once.

Here is my app.js code:

“`
const express = require(“express”);
const bodyParser = require(“body-parser”);
const ejs = require(“ejs”);
const mongoose = require(“mongoose”);

const app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.set(‘view engine’, ‘ejs’);
app.use(express.static(“public”));

// Connect / Create to the Database
mongoose.connect(“mongodb://localhost:27017/stationDB”, { useNewUrlParser: true, useUnifiedTopology: true });

// Create a new Schema
const stnSchema = new mongoose.Schema ({
name: String
});

const contactSchema = new mongoose.Schema ({
name: String,
email: String,
message: String
});

// Create a new Model
const Station = mongoose.model(“Station”, stnSchema);

const Message = mongoose.model(“Message”, contactSchema);

//Creating an array of items to populate the database
const item1 = {
name: “item 1”
};

const item2 = {
name: “item 2”
};

const item3 = {
name: “item 3”
};

const item4 = {
name: “item 4”
};

const stationData = [item1, item2, item3, item4];

//Check the database to see if items have already been inserted, if not then insert the initial items
Station.find({}, function(err, results) {
if (err) {
console.log(err);
}
else {
if (results.length === 0) {
Station.insertMany(stationData), function(err) {
if (err) {
console.log(err);
}
else {
console.log(“No records found – adding initial records”)
}
}
}
else {
console.log(“Records already in place – none added”)
}
}
});

//Routes

// Get Requests

app.get(“/”, function(req, res) {

Station.find({}, function(err, results) {
if (err) {
console.log(“Error: cannot find records for stationList”);
}
else {
const stationList = results;
res.render(“index”, {stationItems: stationList});
}
})

});

// Post Requests

app.post(“/ticketSales”, function(req, res) {
const formSubmit = req.body;
const adultCost = parseFloat(formSubmit.adults) * 7.85;
const childCost = parseFloat(formSubmit.child) * 3.50;
const totalCost = adultCost + childCost;

console.log(totalCost);

res.render(“ticketSales”, {
adults: formSubmit.adults,
adultCost: adultCost,
children: formSubmit.child,
childCost: childCost,
ticketTotal: totalCost,
})
});

app.post(“/contact”, function(req, res) {

const formName = req.body.name;
const formEmail = req.body.email;
const formMsg = req.body.message;

const message = new Message({
name: formName,
email: formEmail,
message: formMsg
});
console.log(message);

message.save();

res.render(“contact”);

});

// App Listen

app.listen(3000, function() {
console.log(‘Server started, port 3000’); //
});
“`

HTML:

“`
<form name=”contact-form” action=”/contact” method=”post”>

<label for=”contact-name”>Name</label>
<input id=”contact-name” name=”name” type=”text”>

<label for=”email”>Email</label>
<input id=”email” name=”email” type=”text”>

<label for=”contact-msg”>Message</label>
<textarea name=”message” id=”contact-msg”>

</textarea>

<button type=”submit” value=”contact” name=”contactBtn”>Submit</button>

</form>
“`

I’m still very new to this and learning but any help would be much appreciated. The only progress I have made is to note that the initial records which are used to populate a drop down in a form do not duplicate when inserted / retrieved but the records sent via post requests are effected. I believe it is related to the post request. Additionally I have found changing the form submit button from to reduces the number of submissions from 4 to 2 – could the html form be the culprit?

to post a comment
HTMLJavaScript

7 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumSep 10.2020 — Unfortunately I do not understand your last sentence:
>Additionally I have found changing the form submit button from to reduces the number of submissions from 4 to 2 - could the html form be the culprit?

Can you explain more detailed?
Copy linkTweet thisAlerts:
@simon_cauthorSep 10.2020 — @Sempervivum#1623176 Sorry typo. I changed the button from <button> to <input type="submit"> which reduced the number of form submissions by 2 for some reason
Copy linkTweet thisAlerts:
@SempervivumSep 10.2020 — I see. Is the HTML form you posted complete? If you changed the button to <input type="button"> there is no way left to submit the form apart from another submit button or submitting the form by javascript.
Copy linkTweet thisAlerts:
@simon_cauthorSep 10.2020 — It is <input type="submit" value="Submit">

I am going to look at submitting with javascript next but I thought this way would be easier
Copy linkTweet thisAlerts:
@SempervivumSep 11.2020 — Using javascript was not a recommendation. I assumed that your button read <input type="button"> and I searched for an explanation how the form is submitted when there is no submit button.
Copy linkTweet thisAlerts:
@simon_cauthorSep 11.2020 — I think I have located the problem, although I am not sure yet what to do about it. I started a new form and added my form inputs one by one. Everything works perfectly until I add the textarea and then I get four submissions instead of the desired one.
Copy linkTweet thisAlerts:
@simon_cauthorSep 11.2020 — I have copied and pasted a textarea example from w3schools just to make sure my syntax is right and this still causes the problem to occur. Remove the textarea and everything runs as it should.
×

Success!

Help @simon_c spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 3.28,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,

tipper: Anonymous,
tipped: article
amount: 10 SATS,
)...