How to call a node.js function from an express rendered ejs webpage

Problem

I have an express server that has a button that issues a POST which activates a function in my node.js server.

Instead of sending a post, I would like to do something kind of like AJAX because I don't want a new page to load. If I use a Javascript button, is there a way I can directly call a function defined in the node.js server instead of having to send a post?

I noticed that JSON values can be passed into the .ejs webpage when it's rendered, but I haven't been able to get it to work for functions.

Problem courtesy of: node ninja

Solution

You can use Socket.io to emit an event from the browser, and than listen for that event on the server to act on it.

Socket.io works flawlessly with express http://socket.io/#how-to-use

Solution courtesy of: levi

Discussion

Take a look at nowjs. It lets you very easily invoke functions on the server from the client and vice-versa:

From the site:

  • NowJS creates a magic namespace "now", accessible by server and client
  • Functions and variables added to now are automatically synced, in real-time
  • Call client functions from the server and server functions from client
Discussion courtesy of: jimr

This recipe can be found in it's original form on Stack Over Flow.