最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - To submit a form without redirecting to other page - Stack Overflow

programmeradmin8浏览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=".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>

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./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./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.

Share Improve this question edited Feb 3, 2018 at 9:09 phuzi 13.1k4 gold badges29 silver badges59 bronze badges asked Feb 3, 2018 at 8:47 Alpit AnandAlpit Anand 1,2584 gold badges22 silver badges42 bronze badges 11
  • 2 Short answer: do an AJAX request. – jrd1 Commented Feb 3, 2018 at 8: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 Commented Feb 3, 2018 at 8: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 Commented Feb 3, 2018 at 8:53
  • 1 Yes, my mistake, editing the post. – Alpit Anand Commented Feb 3, 2018 at 8:54
  • 1 The submit handler should be on the form, not the submit button. – Barmar Commented Feb 3, 2018 at 9:02
 |  Show 6 more ments

3 Answers 3

Reset to default 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./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./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 acplish 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./jquery.ajax/ or https://api.jquery./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./serializeArray/.

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

Hope this will help you solve your issue.

发布评论

评论列表(0)

  1. 暂无评论