Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call node.js server side method from javascript?

I'm new to node.js but I know somewhat about socketstream web framework by using this I can easily call a server side node.js method from JavaScript. I don't know how to do this without using that framework. How can I call the node.js method from JavaScript?

The below code is using socketstream to call server side method. So I want to call the same server side method without using this framework.

ss.rpc('FileName.methodName',function(res){ 
    alert(res);         
});
like image 523
user1629448 Avatar asked Feb 19 '13 06:02

user1629448


People also ask

Can we call server-side function from JavaScript?

In order to call a Server Side function from JavaScript, it must be declared as static (C#) and Shared (VB.Net) and is decorated with WebMethod attribute. Then the Server Side method can be easily called with the help of ASP.Net AJAX PageMethods and JavaScript without PostBack in ASP.Net.

Can we use JavaScript for server-side scripting node JS?

JavaScript is a programming language, it can be run in a number of different environments. Most people run into it in browsers but it can also be used at the command-line via Rhino or currently on the server-side using Node. js Since it's inception back in 1996 JavaScript has been able to run on the server-side.


1 Answers

I'd suggest use Socket.IO

Server-side code

var io = require('socket.io').listen(80); // initiate socket.io server

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' }); // Send data to client

  // wait for the event raised by the client
  socket.on('my other event', function (data) {  
    console.log(data);
  });
});

and client-side

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost'); // connec to server
  socket.on('news', function (data) { // listen to news event raised by the server
    console.log(data);
    socket.emit('my other event', { my: 'data' }); // raise an event on the server
  });
</script>

Alternatively, you can use a router function which calls some function on specific request from the client

var server = connect()
    .use(function (req, res, next) {
      var query;
      var url_parts = url.parse(req.url, true);
      query = url_parts.query;

      if (req.method == 'GET') {
        switch (url_parts.pathname) {
            case '/somepath':
            // do something
            call_some_fn()
            res.end();
            break;
          }
        }
    })
    .listen(8080);

And fire AJAX request using JQuery

$.ajax({
    type: 'get',
    url: '/somepath',
    success: function (data) {
        // use data
    }
})
like image 89
Salman Avatar answered Sep 21 '22 06:09

Salman