Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Node.js how do I communicate with client side JavaScript?

For example suppose client side I have a JavaScript function

function getLocation() {
    var latitude = ...;
    var longitude = ...;
}

The coordinates are retrieved using a function call to Google or similar. How can I transmit this information to my Node.js server?

like image 272
Hoa Avatar asked Jun 20 '12 08:06

Hoa


2 Answers

The easiest way? Set up Express and have your client side code communicate via Ajax (for example, using jQuery).

(function() {
  var app, express;

  express = require("express");

  app = express.createServer();

  app.configure(function() {
    app.use(express.bodyParser());
    return app.use(app.router);
  });

  app.configure("development", function() {
    return app.use(express.errorHandler({
      dumpExceptions: true,
      showStack: true
    }));
  });

  app.post("/locations", function(request, response) {
    var latitude, longitude;
    latitude = request.body.latitude;
    longitude = request.body.longitude;
    return response.json({}, 200);
  });

  app.listen(80);

}).call(this);

On the client side, you might call it like this:

var latitude = 0
  , longitude = 0; // Set from form

$.post({
  url: "http://localhost/locations",
  data: {latitude: latitude, longitude: longitude},
  success: function (data) {
    console.log("Success");
  },
  dataType: "json"
});

Note this code is simply an example; you'll have to work out the error handling, etc.

Hope that helps.

like image 56
Matthew Ratzloff Avatar answered Oct 18 '22 21:10

Matthew Ratzloff


By making an HTTP request, just like you would with any other server side program in a web application.

You could do this with the XMLHttpRequest object, or by generating a <form> and then submitting it, or a variety of other methods.

like image 35
Quentin Avatar answered Oct 18 '22 20:10

Quentin