I don't know if this is possible or not. All the research I've done has shown that it is possible with a form and text input. But anyways, Using NodeJs & Express I want to be able to click a button on my webpage, and once it's clicked, it sends a post request to my Node.JS server.
Simpler way of saying it: When button is clicked, send info to the server.
Goal I'm trying to achieve: When button is clicked, it sends some sort of ID/code/anything to turn on a service from my database. (I have yet to learn how db's work so I am just trying to focus on front end.)
Code I have so far:
app.post("/send", function(req, res){
var newID = req.body.ID;
res.redirect("/action")
});
<form action="/send" method="POST">
<input type="button" name="newID" placeholder="Button">
<button>send</button>
</form>
The formmethod attribute is only used for buttons with type="submit" . The form-data can be sent as URL variables (with method="get" ) or as HTTP post (with method="post" ). Notes on the "get" method: it appends the form-data to the URL in name/value pairs.
Example code: var request = require('request') var options = { method: 'post', body: postData, // Javascript object json: true, // Use,If you are sending JSON data url: url, headers: { // Specify headers, If any } } request(options, function (err, res, body) { if (err) { console. log('Error :', err) return } console.
Part 2 - Handling button clicks and serving fileslog('Server-side code running'); const express = require('express'); const app = express(); // serve files from the public directory app. use(express. static('public')); // start the express web server listening on 8080 app. listen(8080, () => { console.
You do not need to use jQuery or AJAX.
Simply add an input
of type submit
inside the form
tag so that the POST request defined by your form
tag is submitted.
Your newID
input should be of type text
, this allows entering a value in the input field.
The newID
value can be retrieved server side with req.body.newID
(be sure to use the body-parser middleware).
<form action="/send" method="POST">
<input type="text" name="newID" placeholder="Enter your ID"/>
<input type="submit" value="Click here to submit the form"/>
</form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With