I was giving a try to socket.io by creating a live chat, and the page refreshes itself when the message is submitted, here is the markup and the client side JS (index.html):
<body>
<h1>Open chat</h1>
<form id="send_message">
<div class="chat">
</div>
<hr />
<input size="28" type="text" id="message" />
<input type="submit" value="send" />
</form>
<script src="http://code.jquery.com/jquery-latest-min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
JQuery(function($){
var socket = io.connect();
var $message_form = $('#send_message');
var $message_box = $('#message');
var $chat = $('#chat');
$message_form.submit(function(e){
e.preventDefault();
socket.emit('send message', $message_box.val());
$message_box.val('');
})
});
socket.on('new message', function(data){
$chat.append(data+'<br />');
});
</script>
</body>
and here is the server side js (app.js):
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(3000);
app.get('/',function(req, res){
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection',function(socket){
socket.on('send message', function(data){
io.sockets.emit('new message',data);
});
});
I know you guys won't need this but this is package.json:
{
"name":"test_chat_application",
"version":"0.0.1",
"private":"true",
"dependencies":{
"socket.io":"1.4.8",
"express":"4.14.0"
}
}
basically i think the problem is the page refresh! please help..
You have to ditch the form, update some of the stuff (like var socket = io() instead of var socket = io.connect() and stuff) and handle your send button with onclick events instead of form submissions. That way you won't refresh.
Anyway, the updated server.js:
index.html
Try this and let me know if it works
Also move
chat
container outside ofform#send_message
and usedocument.ready
this should work well
better way
As you are using socket (which kind of ajax) - you loose all benefits of form element, so simply don't use it
I think you should add
return false
to prevent the form from being 'really' submitted (and thus refreshing the page). Submit event is not bubbling I think, so e.preventDefault doesn't work in this case.