0

My aim here is to create a HTML form that when you submit 2 numbers they are added together server side in node.js and the answer is displayed in a readonly input field in the same HTML page. At present, my function outputs the answer in a separate page- I don't want to redirect the user, just show the answer on the same page while doing the calculation server side.

My current app.js:

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var app = express();

app.set('port', process.env.PORT || 8080);

app.use(bodyParser.urlencoded({extended: true}));

app.use(express.static(path.join(__dirname, '../static')));

app.get('/', function(req, res){
  res.redirect('/public');
});

app.post('/add', function(req, res){
  var a = parseFloat(req.body.numa);
  var b = parseFloat(req.body.numb);
  var sum = a+ b;
  res.send('Sum: ' + sum);
});

var server = app.listen(app.get('port'), function(){
  var port = server.address().port;

});

my HTML:

<!DOCTYPE html>
<html>
<head>
  <title>hello</title>
</head>
<body onload="testFunc()">

  <h1>Public page</h1>

<form action="/add" method="post">
  Number 1:
  <input type="number" name="numa" step="any"/><br>
  Number 2:
  <input type="number" name="numb" step="any"/><br>
  <input type="number" name="answer" readonly/>
  <input type="submit" value="Submit"/>
</form>
</body>
</html>

I've looked through other posts but the solutions all work through doing it with pug or jade, is there any way to do this without? Any suggestions on what direction I should take would be appreciated! Thank you.

1
  • You'd have to use ajax if you don't want to redirect, a serverside templating language won't help. Commented Jul 20, 2017 at 15:13

3 Answers 3

4

Use Jquery Ajax on client side bodyParser on server side:

Client side:

<form id="myForm" method="post">
  Number 1:
  <input type="number" id="numa" name="numa" step="any"/><br>
  Number 2:
  <input type="number" id="numb" name="numb" step="any"/><br>
  <input type="number" id="answer" name="answer" readonly/>
  <input type="submit" value="Submit"/>
</form>
<div id="result"></div>
<script>
    $(document).ready(function(){
        $("#myForm").submit(function(event){
            event.preventDefault();
            var num1 = $('#numa').val();
            var num2 = $('#numb').val();
            $.ajax({
                method: 'post',
                url: '/data',
                data: JSON.stringify({ num1: num1, num2: num2 }),
                contentType: 'application/json',
                success: function(data) {
                    $('#answer').val(data);
                }

            })
        });
    });
</script>

And Server side:

app.use(bodyParser.urlencoded({  //   body-parser to
    extended: true               //   parse data
}));                             //
app.use(bodyParser.json());      //


app.post('/data', function(req, res) {
    var a = parseFloat(req.body.num1);
    var b = parseFloat(req.body.num2);
    res.send(sum.toString());

})
Sign up to request clarification or add additional context in comments.

1 Comment

Any chance you know the equivalent syntax in vanilla javascript, not jquery? I've looked everywhere but no luck, if you could point me in the right direction that would be great, otherwise thanks anyway!
0

Use client side JavaScript to perform an action when the submit button is clicked and have it retrieve the value rather than redirecting to the /add page. The following being the general idea:

$("submit").onClick(function(){
    $.get("/add", {numa: a, numb: b}, function(err, response, body){
        $("answer").val = body;
    });
});

1 Comment

Is this keeping the post function which adds the inputs in the node js file or is that to be done client side?
0

please check below for your fix https://stackoverflow.com/a/45235894/3490058

in short you have to disable automatic (native) form submission which you can do by adding onsubmit event and removing button click event as it'll submit your form and give you error from nodejs.

<form id="add" method="post" onsubmit="return add()">
  Number 1:
  <input type="number" id="numa" name="numa" step="any"/><br>
  Number 2:
  <input type="number" id="numb" name="numb" step="any"/><br>
  <input type="number" id="answer" name="answer" readonly/>
  <input type="submit" value="Submit"/>
</form>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.