how to call function on the basis of particular button in node.js express
You can use AJAX or WebSockets:
AJAX:
(I assume you have jQuery)
html:
<button id='button1'> Test </button>
js(client):
$('#button1').click(function(){
console.log('button clicked');
$.ajax({url: 'test1', success:function(res){
console.log('server response is', res);
}});
});
js(server):
function buttonAction1(res){
res.send('ok');
}
router.get("/test1", function (req, res) {
buttonAction1(res);
});
WebSockets:
I prefer using something like socket.io. Here is some tutorial you can use.
How do i run a node specific function on button click
You should run node-main.js as a server that receives fetch requests from your client. You're trying to run server-side scripts on the client.
Try using Express.js
https://expressjs.com/
Detect button click with Node.JS
clientside:
$('button').click(function () {
$.post('/thing', {data: 'blah'}, function (data) {
console.log(data);
});
}, 'json');
serverside:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlEncoded());
app.post('/thing', function (req, res, next) {
var data = myFunction(req.body);
res.json(data);
});
Related Topics
How to Reload a Page With React-Router
How to Get Only 1St Element of Json Data
Loading Screen Gets Stuck While Processing Http Request
Regex in JavaScript Allow Only Numbers and One Dot Followed by Max 2 Number
How to Show Which Question a User Is on When Taking My Quiz
Regex for Names Validation Allow Only Letters and Spaces
Check If Page Gets Reloaded or Refreshed in JavaScript
How to Add Multiple Values in Json Object and Get an Updated Json File
How to Get the Name of the Current Windows User in JavaScript
Regex to Replace Everything Except Numbers and a Decimal Point
Foreach Is Not a Function Error With JavaScript Array
How to Make a Bot Delete Messages After a Certain Time Period
How to Remove Forward and Backward Slashes from String in JavaScript
How to Correctly Use Axios Params With Arrays
How to Use Js to Open an HTML Select to Show Its Option List
How to Simulate Key Press Events Programmatically