I would like to:
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);
});
});
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});
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With