socket.io chat example doesn't work after form submit - javascript

I followed the chat tutorial from socket.io (http://socket.io/get-started/chat/), but once I come to the part I have to get information from the form I get stuck.
The warnings I get from my index.html file are:
io is not defined please fix or add global io
$ is not defined please fix or add global $
I tried adding the website link to the <script src="/socket.io/socket.io.js"> however this had no effect. I am using c9.io as my development tool. using node.js and socket.io.
index.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
http.listen(process.env.PORT, process.env.IP, function() {
console.log("listening on *:" + process.env.PORT);
});
index.html
<!-- I did not include the html and head tags in this example for readability purposes -->
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
</body>

Add event window ready
var socket = io();
$(document).ready(function(){
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
});

Related

Socket.emit not going through

index.js
var app = require('express')();
var path = require('path');
var server = require('http').Server(app);
var io = require('socket.io')(server);
var users = [];
connections = [];
server.listen(process.env.PORT || 3000);
app.use(require('express').static(path.join(__dirname)));
console.log('server running');
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
var addedUser = false;
socket.on('new post', function(post){
console.log(post);
socket.emit('posted', data);
});
});
client.js
$(function(){
function submit(){
socket.emit('new post', $("#text").val());
console.log("submitted");
}
function addPost(data){
console.log(2);
var $post = $('<p></p>').text(data);
console.log($post);
$("#posts").append($post);
}
$("#submit").on("click", function(){
submit();
});
socket.on('posted', function(data){
console.log(1);
addPost(data);
});
});
index.html
<html>
<head>
<title>title</title>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="text">Input</input>
<button id="submit">Submit</button>
<script src="client.js"></script>
<br>
<br>
<br>
<div id="posts"></div>
<script>
var socket = io();
</script>
</body>
</html>
When I start up the server, the console logs "server running" fine. I can't get the submit post button to do anything. None of the debug console messages appear and nothing happens. It's supposed to emit "new post" when the submit button is clicked but it looks as if nothing goes through
I was able to get your code to work on my own computer like this:
index.js
var express = require('express');
var app = express();
var path = require('path');
var server = require('http').Server(app);
var io = require('socket.io')(server);
var users = [];
connections = [];
app.get('/', function(req, res){
res.sendFile(path.join(__dirname, 'index.html'));
});
app.use(express.static(__dirname));
console.log('server running');
io.on('connection', function (socket) {
console.log("connection");
socket.on('new post', function(post){
console.log(post);
socket.emit('posted', post);
});
});
server.listen(process.env.PORT || 3000);
client.js
$(function(){
function submit(){
socket.emit('new post', $("#text").val());
console.log("submitted");
}
function addPost(data){
console.log(2);
var $post = $('<p></p>').text(data);
console.log($post);
$("#posts").append($post);
}
$("#submit").on("click", function(){
submit();
});
socket.on('posted', function(data){
console.log(1);
addPost(data);
});
});
index.html
<html>
<head>
<title>title</title>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="text">Input</input>
<button id="submit">Submit</button>
<script src="/client.js"></script>
<br>
<br>
<br>
<div id="posts"></div>
<script>
var socket = io();
</script>
</body>
</html>
Changes to index.js
Define express variable so it can be reused.
Define app.get() before app.use(express.static(...)) so we're sure to serve index.html with the app.get() and not from the static location.
Change res.sendfile() to res.sendFile()`
Change socket.emit("posted", data) to socket.emit("posted", post).
Move server.listen() to end after everything else is set up.
Remove path.join() from express.static() call since it is not needed there.
Add path.join() to res.sendFile() call for cross platform safety in path building.
Of these, the only one I'm sure was causing an error was #4, the others are good housekeeping.
Changes to client.js
None
Changes to index.html
Change path to client.js to /client.js.
If this code doesn't work on heroku, then you either don't have files positioned in the right directories or heroku is not configured properly to allow your app or socket.io to work properly. If I were you, I would first verify that this code work on your own local computer and only then, go try it on heroku to eliminate variables first.

Node.js chat app with username variables not working

I'm making a chat app in node.js based on a tutorial from socket.io. The purpose is for a user to enter in a username and a message. The chat will display "username: message". The username text field will then disappear after the first entry. I have it all working except for the chat displaying the message with the username. The chat displays four messages instead of one, they say that both variables are undefined.
JS
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
io.on('connection', function(socket){
socket.on('chat message', function(msg, usn){
io.emit('chat message', msg);
io.emit('chat message', usn);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
HTML (Without the style tags)
<!doctype html>
<html>
<head>
<title>Lucas Chat</title>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="u" autocomplete="off" placeholder="Nickname"/><input id="m" autocomplete="off" placeholder="Message"/><button>Send</button>
</form>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
socket.emit('chat message', $('#u').val());
$('#u').css("display", "none")
$('#m').css("width", "90%")
$('#m').val('');
return false;
});
socket.on('chat message', function(msg, usn){
$('#messages').append($('<li>').text(usn + ": " + msg));
});
</script>
</body>
</html>
clientside
var socket = io();
$('form').submit(function(){
socket.emit('send message', {msg:$('#m').val(),user:$('#u').val()});
$('#u').css("display", "none")
$('#m').css("width", "90%")
$('#m').val('');
return false;
});
socket.on('receive message', function(msg){
$('#messages').append($('<li>').text(msg));
});
and serverside
io.on('connection', function(socket){
socket.on('send message', function(data){
io.emit('receive message',data.msg + ':' + data.user);
});
});

Socket.io socket.emit not passing data to server

I was trying my hands on Socket.io.
I have the following code.
This is my index.html.
<!doctype html>
<html>
<body>
<ul id="messages"></ul>
<form action="" onsubmit="return sayHello()">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script>
var socket = io.connect('http://127.0.0.1:3001/');
function sayHello(){
var msg = document.getElementById('m');
console.log(msg); <- This is getting printed.
socket.emit('message', msg.value);
msg.value='';
return (false);
}
// $('form').submit(function(){
// socket.emit('chat message', $('#m').val());
// $('#m').val('');
// return false;
// });
// socket.on('chat message', function(msg){
// $('#messages').append($('<li>').text(msg));
// });
</script>
</body>
</html>
This is my server.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log("GO!") <- This is getting printed
socket.on('chat message', function(msg){
console.log(msg); <- This is not getting printed.
io.emit('chat message', msg);
});
});
http.listen(3001, function(){
console.log('listening on *:3001');
});
I have cloned the sample project from the Socket.io website. I was trying to modify some code by replacing the Jquery with VanillaJS.
You are listening for chat message but emitting message from client. Event name provided with .emit must match with the event name being listened on the server in .on handler.
//SERVER SIDE CODE
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket) {
console.log("GO!") < -This is getting printed
socket.on('chat message', function(msg) {
console.log(msg); < -This is not getting printed.
io.emit('chat message', msg);
});
});
http.listen(3001, function() {
console.log('listening on *:3001');
});
<!doctype html>
<html>
<body>
<ul id="messages"></ul>
<form action="" onsubmit="return sayHello()">
<input id="m" autocomplete="off" />
<button>Send</button>
</form>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script>
var socket = io.connect('http://127.0.0.1:3001/');
function sayHello() {
var msg = document.getElementById('m');
console.log(msg); < -This is getting printed.
socket.emit('chat message', msg.value);
//-----------^^^^^^^^^^^^ Event name must match with the `.on` listener on the server!
msg.value = '';
return (false);
}
</script>
</body>
</html>

Socket.io: Node.js can't receive event message via method socket.on('message', ...) on AWS

I'm having this problem even with the Socket.io official chat sample.
I had this set up on AWS. I could only received the 'successfully connected' message on the terminal but not the 'message: ....'. Even with Google Dev Tool I couldn't saw any related error. Anyone could help?
Here's the client side javascript code:
<script src="https://cdn.socket.io/socket.io-1.3.4.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
</script>
Then the server side node.js code:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('index.html');
});
http.listen(8989, function(){
console.log('listening on *:8989');
});
io.on('connection', function(socket){
console.log('successfully connected');
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
});
There is no form submit on button click, also form submit will create a lot of page refreshes and everything, and also you dont need a form for this exercise
Create a function sendMessage()
<script>
var socket = io();
function sendMessage(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
}
</script>
In your HTML remove form and add onclick to button
<body>
<ul id="messages"></ul>
<input id="m" autocomplete="off" /><button onclick="sendMessage()">Send</button>
</body>
It turned out the problem was on the client side javascript code.
I referred to this sample code and found that on socket.io official website it says in some cases (Express 3/4 or the framework) you need to use io.connect() instead of io(). However it works for me in my previous case.
Here's the changed code:
var socket = io.connect();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});

Using disconnect function on socket.io and node.js

I am trying to have it so when a user disconnects from my chat room, it pops up with " has left chat room".
Here is my server code:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('chat/index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
socket.on('disconnect', function(nickname){
io.emit('disconnect', nickname);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
And here is my client code:
var socket = io();
var nickname;
var leaving;
$('messageForm').submit(function(){
socket.emit('chat message', (nickname + ": " + $('#m').val()));
$('#m').val('');
return false;
});
$('#nicknameForm').submit(function(){
nickname = $('#nickname').val();
if(nickname ==''){
alert("Please enter a value");
}else{
$( "#dialog" ).dialog( "close" );
leaving = nickname + " has left";
}
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
socket.on('disconnect', function(nickname){
socket.emit('disconnect message', nickname);
});
At the moment, nothing appears at all, and I'm not too sure why.
You need to emit a unique event to the clients when another client disconnects.
Change the following:
socket.on('disconnect', function() {
io.emit('disconnect', nickname);
});
To something like this:
socket.on('disconnect', function() {
socket.broadcast.emit('user disconnect', nickname);
});
And add this to your client code:
socket.on('user disconnect', function(nickname){
$('#messages').append($('<li>').text(nickname+' has left the channel.'));
});

Categories