I'm currently building a small chat.
When someone hits enter, it should submit the message to the server and return some status info if inserting was successful.
Is there a way to return some data on every event or do I have to initiate another send from the server to notifiy the client about the status?
Client
$('textarea').keypress(function(e) {
if(e.which == 13) {
var msg = $.trim(this.value);
if(msg.length > 0) {
socket.send(msg, function() {
// Here I need to have some result
// returned by the server to notify the user
// if everything went fine
//this.value = '';
});
}
return false;
}
});
Server
socket.on('message', function() {
db.query("INSERT INTO chat (message, ip, time) VALUES (?, INET_ATON(?), NOW())", [msg, socket.handshake.headers['x-forwarded-for'] || socket.handshake.address.address], function(error) {
if(!error) {
io.sockets.send(msg);
} else {
console.log(error);
}
});
});
I ran into this issue recently. My solution was to put a command ID into every message. I built a little function to make an ID on the client side (here). So the flow looks like this:
Client
Server
Client
Code for the server side step:
socket.on 'du', (msg) =>
@saveData(msg, ->
# broadcast to other users if needed
socket.emit('cc', msg.data.commandId)
)