33

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.

Any help?

IMPROVED QUESTION:

//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-->
6
  • 4
    You need to communicate with the server over HTTP, using AJAX or a form POST or websockets. Commented Sep 16, 2013 at 15:32
  • I have googled alot, but unable to get the correct example, Commented Sep 16, 2013 at 15:40
  • @SaadAbdullah: What don't you understand? Node.js is a much thinner web platform; you need to understand the underlying technologies (HTML and HTTP). Commented Sep 16, 2013 at 15:42
  • @SLaks: thanx for your response sir, I am making replica of wikipedia for my web-programming semester project, (means, I am a noob with node.js) I am stuck at some point, I just want to know that how can i use the server side function from client side event? Commented Sep 16, 2013 at 15:54
  • 1
    @SaadAbdullah: You can't call a function on one computer from another computer. You need to send a request over the network. Commented Sep 16, 2013 at 19:49

1 Answer 1

48

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);

The code above will start an instance of Express, which is a web application framework for Node. The bodyParser() module is used for parsing the request body, so you can read post data. It will then listen for POST requests on the route /.

<form method="post" action="/">
  <input type="test" name="field1">
  <input type="test" name="field2">
  <input type="submit">
</form>

And if you submit that form, in req.body for the route /, you will get the result:

{ field1: 'form contents', field2: 'second field contents' }

To run a function, just put it inside the POST handler like this:

var foo = function() {
  // do something
};

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

  // sending a response does not pause the function
  foo();
});

If you don't want to use Express then you can use the native HTTP module, but you'd have to parse the HTTP request body yourself.

var http = require('http');
http.createServer(function(request, response) {
  if (request.method === 'POST') {
    var data = '';

    request.on('data', function(chunk) {
      data += chunk;
    });

    request.on('end', function() {
      // parse the data
      foo();
    });
  }
}).listen(80);
Sign up to request clarification or add additional context in comments.

5 Comments

where is app.get function?
This is an example, not a full solution. You can find out how to use it in the documentation: expressjs.com
I have checked the API, I cannot find any example regarding calling server side function. but thanx for your answer :)
app.use(bodyParser()); //Now deprecated You now need to call the methods separately app.use(bodyParser.urlencoded()); app.use(bodyParser.json()); - stackoverflow.com/questions/24330014/…
There was no example showing how a script is named in an onClick statement that is served by Express.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.