I have been trying to make an online HTML form, which could submit the form and post the data to the local database. However, I don't want the page to be redirected to /formfill
URL and send the data to DB without redirecting the page. I have been trying a lot. However, no luck.
Here is my backend node.js code:
// require('./../config.js');
const express = require('express');
const path = require('path');
var bodyParser = require('body-parser');
var app = express();
var {
mongoose
} = require('./models/mongoose.js');
var {
Data
} = require('./models/form.js');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, '..', 'public')));
app.post('/formfill', function (req, res) {
var data = new Data({
name: req.body.name,
mailId: req.body.mailId
})
data.save().then((doc) => {
res.status(200).send(doc);
}).catch((e)=>{
res.status(400).send(e);
})
})
app.listen(3000, () => {
console.log("Server is up");
});
Here is my Html form:
<form action="/formfill" method="POST" , enctype="application/x-www-form-urlencoded">
<input class="formfill" type="text" name="name" placeholder="Your name">
<br>
<input class="formfill" type="text" name="mailId" placeholder="Your email">
<br>
<input id="submit-button" class="formfill sumbit-button" type="submit" value="Submit">
</form>
And here is my JavaScript code, tried with AJAX too:
$(function() {
$("#submit-button").submit(function(e) {
e.preventDefault();
return false;
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/formfill" method="POST" , enctype="application/x-www-form-urlencoded">
<input class="formfill" type="text" name="name" placeholder="Your name">
<br>
<input class="formfill" type="text" name="mailId" placeholder="Your email">
<br>
<input id="submit-button" class="formfill sumbit-button" type="submit" value="Submit">
</form>
With AJAX:-
$(function() {
$("#submit-button").submit(function(e) {
e.preventDefault();
var formData = new FormData($(this));
$.ajax({
url: '/formfill',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function(response) {
console.log(response);
}
});
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/formfill" method="POST" , enctype="application/x-www-form-urlencoded">
<input class="formfill" type="text" name="name" placeholder="Your name">
<br>
<input class="formfill" type="text" name="mailId" placeholder="Your email">
<br>
<input id="submit-button" class="formfill sumbit-button" type="submit" value="Submit">
</form>
All I want to do is submit the form without being redirected to /formfill
or refreshing the page.