Stephen Stephen - 6 months ago 10
Node.js Question

NodeJS Post request using a Button

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>

Answer

For this purposes you should use $.ajax, example:

$('button').on('click', function() {
    $.ajax({
      type: 'POST',
      url: '/send',
      data: { ID: 'someid' },
      success: function(resultData) {
         alert(resultData);
      }
    });
});