Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST data through socket.io to app.js

I would like to:

  • retrieve data entered from input forms.
  • send the data through socket.io and send console log saying done
  • receive the data on express app.js
  • insert the data into a mongodb database using mongoose.

I understand emit messages but not sure how to post data through. thank you in advance

my app.js is set up like this:

//app.js config ...

var socket = io.listen(server);

socket.on('connection', function(socket) {
   console.log('socket.io connected');
});



app.post('/go', function(req, res) {

  socket.on('data', function(data) {
    new Order({
      routeFrom : data.routeFrom,
      routeTo : data.routeTo,
      leaving: data.leaving
    }).save(function(err, docs) {
      if(err) { console.log("error"); }
      res.json(data);
    });
    socket.emit('callback', {done: 'Done'});
  });

});

my index.ejs file:

  <script src="/socket.io/socket.io.js"></script>

 var socket = io.connect('http://localhost:3000');

$('#send').on('click', function() {
    $.post('/go', {
       socket.emit('data', {
        routeFrom: $('#rf').val(),
        routeTo: $('#rt').val(),
        leaving: $('#l').val()
       });

    });

  socket.on('callback', function(data) {
   console.log(data);
  });

});

like image 856
ashley Avatar asked Dec 10 '12 14:12

ashley


1 Answers

You don't need POST at all.

I would do on the client side:

var socket = io.connect('http://localhost:3000');

$('#send').on('click', function(event) {
  event.preventDefault();
  socket.emit('data', {
    routeFrom: $('#rf').val(),
    routeTo: $('#rt').val(),
    leaving: $('#l').val()
  });
});

socket.on('callback', function(data) {
  console.log(data.done);
  // Print the data.data somewhere...
});

And on the server side:

//app.js config ...
var socket = io.listen(server);

socket.on('connection', function(socket) {
  console.log('socket.io connected');
});

socket.on('data', function(data) {
  new Order({
    routeFrom : data.routeFrom,
    routeTo : data.routeTo,
    leaving: data.leaving
  }).save(function(err, docs) {
    if(err) { return console.log("error"); }
    socket.emit('callback', {done: 'Done', data: data});
  });
});
like image 55
maxdec Avatar answered Sep 25 '22 08:09

maxdec