1

So this is a slight follow up to a question I had yesterday (Update HTML input value in node.js without changing pages), I'm attempting to submit a HTML form, send an ajax request to my server which supplies two numbers, these numbers are added on the server and then shown in a box on the same HTML page as the form. So far I received a solution in JQuery which was extremely useful, however my manager wants it done in javascript for various reasons. I've had a go so far, but as many people use JQuery for this, examples of a vanilla javascript method are few and far between. At present, on submission a page is thrown saying "Cannot POST /public/", I'm new to ajax so I'm reasonably sure the problem lies there.

My (working) JQuery code:

$(document).ready(function(){
  $("#add").submit(function(event){
    event.preventDefault();
    var num1 = $("#numa").val();
    var num2 = $("#numb").val();
    $.ajax({
      method: "post",
      url: '/add',
      data: JSON.stringify({ num1: num1, num2: num2 }),
      contentType: 'application/json',
      success: function(data){
        $("#answer").val(data);
      }
    })
  })
})

My attempt at converting to javascript:

function add(){
  var xml = new XMLHttpRequest();
  var num1 = document.getElementById("numa");
  var num2 = document.getElementById("numb");
  xml.open("POST", "/add", true);
  xml.setRequestHeader("Content-Type", "application/json");
  xml.onreadystatechange = function(){
    if(xml.readyState == XMLHttpRequest.DONE){
      document.getElementById("answer").value = xml.responseText;
    }
  }
  xml.send(JSON.stringify({num1: num1, num2: num2}));
}

My 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(bodyParser.json());

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.num1);
  var b = parseFloat(req.body.num2);
  var sum = a+ b;
  res.send(sum.toString());
});

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

});

For completion, my HTML form:

<form id="add" 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" onclick="add()"/>
</form>

Any pointers would be great, thanks!

2

1 Answer 1

1

all looks good except the two lines:

var num1 = getElementById("numa");
var num2 = getElementById("numb");

it should be like this

var num1  = document.getElementById("numa");
var num2  = document.getElementById("numb");

Note: updated html code (added onsubmit in form and removed from button)

<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>
Sign up to request clarification or add additional context in comments.

6 Comments

Of course, silly mistake! Fixed that, but I'm still getting the same error?
He also need to take the value of these elements
ofcourse, you have to get values of the elements, i just gave hint this was the line where the error happens..
I've changed the syntax to be var num1 = document.getElementById("numa").value; and still the error is thrown
If you're still having trouble, I found the source of your error, it is in your form tag also. When you click a button in form you're basically submitting form which is a normal form submit. since you have to handle it using javascript , please see my updated code above.
|

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.