Node.Js Call Function If Button Clicked

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



Leave a reply



Submit