0

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.

phuzi
  • 12,078
  • 3
  • 26
  • 50
Alpit Anand
  • 1,213
  • 3
  • 21
  • 37
  • 2
    Short answer: do an AJAX request. – jrd1 Feb 03 '18 at 08:50
  • Yes, i have been tying to do that, its being said on every post like this to perform ajax. But its not working, its still being redirected to the '/formfill' with data of the form displayed in json – Alpit Anand Feb 03 '18 at 08:51
  • 1
    If the consensus is to use AJAX and it's not working, then why haven't you included it in _this_ question? We're here to help you help yourself! – jrd1 Feb 03 '18 at 08:53
  • 1
    Yes, my mistake, editing the post. – Alpit Anand Feb 03 '18 at 08:54
  • 1
    The `submit` handler should be on the form, not the submit button. – Barmar Feb 03 '18 at 09:02
  • Possible duplicate of [Submit a form using jQuery](https://stackoverflow.com/questions/1200266/submit-a-form-using-jquery) – nbrooks Feb 03 '18 at 09:06
  • @Barmar trying your advice – Alpit Anand Feb 03 '18 at 09:07
  • @nbrooks, i stumbled upon that one, however , i was using node and wasn't very sure that it only require frontend – Alpit Anand Feb 03 '18 at 09:08
  • @AlpitAnand in that example provided by nbrooks, the backend (server-side) is irrelevant. You submit the form using Ajax which causes a HTTP request. All server-side languages understand a HTTP request. All you have to do is make sure the request is correct. – ADyson Feb 03 '18 at 09:09
  • @AlpitAnand Submitting the form is front-end js code only, and the only dependency for that linked post is jQuery. Should work just fine for you! – nbrooks Feb 03 '18 at 09:10
  • Yes, i am going to read each and every link provided by you all. Hoping it would shed some light. – Alpit Anand Feb 03 '18 at 09:12

3 Answers3

2

Replace $("#submit-button").submit(function(e) { with $("#submit-button").closest("form").submit(function(e) { :-)

The preventDefault method seems to work :

function customSubmit () {
  $("#on-btn").attr("disabled", "disabled");
  $("#off-btn").removeAttr("disabled");
  $("form").on("submit", function (ev) {
    ev.preventDefault();
    console.log($(this).serialize());
  });
}
function defaultSubmit () {
  $("#off-btn").attr("disabled", "disabled");
  $("#on-btn").removeAttr("disabled");
  $("form").off("submit");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  <button id="on-btn" type="button" onclick="customSubmit()">Custom submit</button>
  <button id="off-btn" type="button" onclick="defaultSubmit()" disabled>Default submit</button>
</p>
<form action="" method="POST">
  <input type="text" name="dummy" value="dummy">
  <input type="submit" name="submit">
</form>
1

async should be true and other details ,,,

     $(function() {
        $("form").submit(function(e) {
            e.preventDefault();
            var formData = new FormData($(this));
            $.ajax({
                url: '/formfill',
                type: 'POST',
                data: formData,
                async: true,
                cache: false,
                contentType: false,
                processData: false,
                success: function(response) {
                    console.log(response);
                }
            });
        })
    });

here is my test code on localhost,that works fine:

<!DOCTYPE html>
<html>

<head>
    <title>d</title>
    <style></style>
    <meta charset="UTF-8">
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
</head>

<body>
    <form action="http://localhost:800/github/test/formfill.txt" 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>
    <script>
    $(function() {
        $("form").submit(function(e) {
            e.preventDefault();
            var formData = new FormData($(this));
            $.ajax({
                url: 'http://localhost:800/github/test/formfill.txt',
                type: 'POST',
                data: formData,
                async: true,
                cache: false,
                contentType: false,
                processData: false,
                success: function(response) {
                    console.log(response);
                }
            });
        })
    });
    </script>
</body>

</html>
xianshenglu
  • 4,943
  • 3
  • 17
  • 34
0

Your BE is good but you will need to update the client code.

You should use Ajax to accomplish this task. Ajax will send an HTTP request via the web API and won't trigger the browsers redirect action (which submit and anchor tag triggers). And I see you are using jQuery so you have see http://api.jquery.com/jquery.ajax/ or https://api.jquery.com/jquery.post/.

The thing is that you will need to get the form data manually (via javascript). You can use jQuery as well https://api.jquery.com/serializeArray/.

jQuery docmintation is really good. you should give it a look.

Hope this will help you solve your issue.

Daniel
  • 2,288
  • 1
  • 14
  • 22