简体   繁体   中英

To submit a form without redirecting to other page

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.

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> 

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM