How to call a server side function from client side (e.g. html button onclick) in Node.js?

Asked
Active3 hr before
Viewed126 times

6 Answers

clientfunctionbuttonserver
90%

I need a complete basic example in Node.js of calling a server-side function from (client side) html button onclick event, just like in ASP.NET and C#. ,I am new to Node.js and using the Express framework.,Here's an example using Express and a HTML form.,ExpressionEngine® Answers

Here's an example using Express and a HTML form.

var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);

app.use(express.bodyParser());
app.post('/', function(req, res) {
   console.log(req.body);
   res.send(200);
});

server.listen(process.env.PORT, process.env.IP);
load more v
88%

How to call a server side function from client side (e.g. html button onclick) in Node.js? ,I need a complete basic example in Node.js of calling a server-side function from (client side) html button onclick event, just like in ASP.NET and C#. ,To run a function, just put it inside the POST handler like this:

//server side :

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var app = express();

// all environments

app.set('views', __dirname + '/views');
app.set('port', process.env.PORT || 3000);
app.engine('html', require('ejs').renderFile);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'html');

app.use(app.router);

app.get("/", function(req, res) {
   res.render('home.html');
});

// development only
if ('development' == app.get('env')) {
   app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/users', user.list);

http.createServer(app).listen(app.get('port'), function() {
   console.log('Express server listening on port ' + app.get('port'));
});

//Client Side

 <input type="button" onclick="" />
 <--just want to call the serverside function from here-->
load more v
72%

Create a folder named node-express-mongo:,Create an empty file named server.js in your folder. Also, create a folder named public and put empty files named index.html and client.js in that folder. The public folder will store our client-side code. server.js will contain our server-side code.,Edit your files to contain the following:,If you have done this correctly there will be no errors from Node.

Project structure:

node - express - mongo / package.json
node - express - mongo / server.js
node - express - mongo / public / index.html
node - express - mongo / public / client.js
<!DOCTYPE html>
<html>

<head>
   <meta charset="utf-8">
   <title>Node + Express + MongoDb example</title>
</head>

<body>
   <h1>Node + Express + MongoDb example</h1>
   <p id="counter">Loading button click data.</p>
   <button id="myButton">Click me!</button>
</body>
<script src="client.js"></script>

</html>
console.log('Client-side code running');

const button = document.getElementById('myButton');
button.addEventListener('click', function(e) {
   console.log('button was clicked');
});
console.log('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.log('listening on 8080');
});

// serve the homepage
app.get('/', (req, res) => {
   res.sendFile(__dirname + '/index.html');
});
console.log('Server-side code running');

const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const app = express();

// serve files from the public directory
app.use(express.static('public'));

// connect to the db and start the express server
let db;

// ***Replace the URL below with the URL for your database***
const url = 'mongodb://user:password@mongo_address:mongo_port/databaseName';
// E.g. for option 2) above this will be:
// const url =  'mongodb://localhost:21017/databaseName';

MongoClient.connect(url, (err, database) => {
   if (err) {
      return console.log(err);
   }
   db = database;
   // start the express web server listening on 8080
   app.listen(8080, () => {
      console.log('listening on 8080');
   });
});

// serve the homepage
app.get('/', (req, res) => {
   res.sendFile(__dirname + '/index.html');
});
console.log('Client-side code running');

const button = document.getElementById('myButton');
button.addEventListener('click', function(e) {
   console.log('button was clicked');

   fetch('/clicked', {
         method: 'POST'
      })
      .then(function(response) {
         if (response.ok) {
            console.log('Click was recorded');
            return;
         }
         throw new Error('Request failed.');
      })
      .catch(function(error) {
         console.log(error);
      });
});
// add a document to the DB collection recording the click event
app.post('/clicked', (req, res) => {
   const click = {
      clickTime: new Date()
   };
   console.log(click);
   console.log(db);

   db.collection('clicks').save(click, (err, result) => {
      if (err) {
         return console.log(err);
      }
      console.log('click added to db');
      res.sendStatus(201);
   });
});
// get the click data from the database
app.get('/clicks', (req, res) => {

   db.collection('clicks').find().toArray((err, result) => {
      if (err) return console.log(err);
      res.send(result);
   });
});
setInterval(function() {
   fetch('/clicks', {
         method: 'GET'
      })
      .then(function(response) {
         if (response.ok) return response.json();
         throw new Error('Request failed.');
      })
      .then(function(data) {
         document.getElementById('counter').innerHTML = `Button was clicked ${data.length} times`;
      })
      .catch(function(error) {
         console.log(error);
      });
}, 1000);
load more v
65%

Note that another option here would be to use the forEach() built-in method available on NodeList objects:,There are many different event handler properties available. Let's experiment.,For example, Node.js is a very popular JavaScript runtime that enables developers to use JavaScript to build network and server-side applications. The Node.js event model relies on listeners to listen for events and emitters to emit events periodically — it doesn't sound that different, but the code is quite different, making use of functions like on() to register an event listener, and once() to register an event listener that unregisters after it has run once. The HTTP connect event docs provide a good example.,You should never use the HTML event handler attributes — those are outdated, and using them is bad practice.

<button>Change color</button>
load more v
75%

Reference counting of thread-safe functions,[in] func: The thread-safe function to unreference.,[in] func: The thread-safe function to reference.,Calling a thread-safe function

Linux and Mac:

$ mkdir~/projects
$ cd~/projects

Windows CMD:

> mkdir % USERPROFILE % \projects >
   cd % USERPROFILE % \projects

Windows PowerShell:

> mkdir $env: USERPROFILE\ projects >
   cd $env: USERPROFILE\ projects

Open hello-world.js in any preferred text editor and paste in the following content:

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
   res.statusCode = 200;
   res.setHeader('Content-Type', 'text/plain');
   res.end('Hello, World!\n');
});

server.listen(port, hostname, () => {
   console.log(`Server running at http://${hostname}:${port}/`);
});

Save the file, go back to the terminal window, and enter the following command:

$ node hello - world.js

Output like this should appear in the terminal:

Server running at http: //127.0.0.1:3000/
load more v
40%

JavaScript can use DOM objects, properties and methods to read and navigate through an XML document like rss-fragment.xml,www.w3.org/TR/2000/WD-DOM-Level-1-20000929/ecma-script-language-binding.html W3C DOM objects, properties and methods in JavaScript ,Javascript scripts can be executed upon, e.g., a script element being encountered in a document (not recommended) event occurrences ,each DOM node object has a number of properties for navigation, e.g.: firstChild nextSibling parentNode childNodes which return, respectively, the first child, next sibling, parent and all children of the node

<script type="text/javascript">
   document.write("<em>Document title</em>: ", document.title);
</script>
load more v

Other "client-function" queries related to "How to call a server side function from client side (e.g. html button onclick) in Node.js?"