Hi guys I am trying to learn the basics of Node.JS and I was wondering if anybody could tell me how to send like a number from a form to a node.js server and then the node.js server sends that value processed in some function back to be inserted in the text box that was used to send the form.
</head>
<script type="text/javascript" scr="views/javascript/jquery-3.1.1.min.js"></script>
<script type="text/javascript" scr="views/javascript/index.js"></script>
<body>
<h1>
Converter
</h1>
<p>
This converter can convert decimal to binary
</p>
<form>
Convert Decimal to Binary:<br>
<input id="inputDecimal" type="text" name="number"<br>
<input id="inputDec" type="submit">
</form>
</body>
server.js
var express = require("express"); var app = express(); var path = require("path");
/* * POST and GET are relative to the client * */ app.get('/',function(req,res){ res.sendFile(path.join(__dirname+'/views/index.html')); //__dirname : It will resolve to your project folder. });
Alright, to be very honest I have no experience with AJAX at all, but I will try to make something of it as I do have a bit of experience with NodeJS (especially Express). I found an example of a form submission on the jQuery documentation page here. Have a look at that. I rewrote that to the following (but I haven't tested it)
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.post to NodeJS demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<form action="/compute" id="conversionForm">
<input type="number" name="n" placeholder="Convert...">
<input type="submit" value="Convert">
</form>
<script>
// Attach a submit handler to the form
$( "#conversionForm" ).submit(function( event ) {
// Stop form from submitting normally
event.preventDefault();
// Get some values from elements on the page:
var $form = $( this ),
number = $form.find( "input[name='n']" ).val(),
url = $form.attr( "action" );
// Send the data using post
$.post( url, { convert: number } );
});
</script>
</body>
</html>
Now we will let this sit for a bit and move on to Node. I use a middleware (something that parses the data that passes through Express) called body-parser. We will use this extension to make sure that your request body is formatted as JSON when it arrives at your app.get() method. Add the latest version of body-parser to your package.json and require it in your server.js. Your server.js will then look something like this (I left out the unnecessary code and used some ES6 syntax where possible)
const express = require("express"),
app = express(),
bodyParser = require("body-parser"),
path = require("path");
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/views/index.html'));
});
app.post('/compute', (req, res) => {
//now because we use bodyParser.json(), this should hopefully print something like
//{convert: 3}
console.log(JSON.stringify(req.body));
//so now we extract the to-be-converted number from the response
const number = parseInt(req.body.convert);
var convertedNumber = //TODO YOUR CONVERSION HERE
res.send(convertedNumber);
});
app.listen(3000, () => {
console.log('Server listening on port 3000...');
});
Remember now, I didn't test this because I'm at work, but from the top of my head, this should work just fine. Let me know ;)