Henry Henry - 11 months ago 43
Node.js Question

Fire on return from form "Submit"

I want to be able to parse values on return from a submit post. I can't seem to find a way to do this without manually initiating an ajax call through javascript

Code on webpage:

<form id="form1" method="post" action="/formSubmit" >
<input type="text" name="username">
<input type="text" name="email">
<input type="submit" value="Submit">

Code on nodejs server:

router.post('/', function(req, res) {
console.log("HERE: " + req.body.username);
console.log("HERE: " + req.body.email);
res.json({ data1: 'Hello', data2: 'World'});

EDIT #1: Currently this just renders "{ data1: 'Hello', data2: 'World'}" into the browser, but I need to parse it

Answer Source

What do you want to see after the form submit? The way you handle the POST request you're sending a JSON. So you would indeed need AJAX to render your result more beautiful. In order to avoid the usage of AJAX you just have to send the response as HTML file.

Of course you can also pass the submitted form data to a template and send it to the user. Pass the variables you need to your template:

res.render('formsubmit', {data1: 'Hello', data2: 'World'}); 

for that you would need to have a template file in your template directory called formsubmit (plus the file ending depending on your view engine) which takes the given variables. Express will take care of creating a HTML file out of it.

E.g. for Handlebars you can access the variables in the template file named formsubmit.hbs in your views folder like:

<p>Hello, my name is {{data}} and not {{data2}}.

See also: https://expressjs.com/en/guide/using-template-engines.html