Nicholas Hendricks Nicholas Hendricks - 23 days ago 9
Node.js Question

socket.username keeps displaying as udefined on my clinet html

I am trying to build a chatroom in node.js and socket.io but when i try to display the users name beside their message it just shows undefined here is my client code

index.html

<html>
<head>
<meta name="viewport" content="width=device-width"/>
<meta name="description" content="BillIsChill-2.0 BETA">
<meta name="keywords" content="billischill,Bill,is,chill,2.0,billischill-2.0,gamer-chat,BillIsChill-Underground-Chat,BILLISCHILL,>
<meta name="author" content="Nik Hendricks">
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>

<script src="/socket.io/socket.io.js"></script>
<title>BillIsChill-2.0</title>
<link type="text/css" rel="stylesheet" href="http://billischill.ddns.net/billischill-2.0/css/masterStyle.css" />
<link type="text/css" rel="stylesheet" href="http://billischill.ddns.net/billischill-2.0/css/animate.css" />
</head>
<body>
<div id="main-header-div">
<p id="main-header-div-text">BillIsChill-2.0<p>
<form>
<input id="main-header-div-search-txtinpt" class="search" placeholder="Search" name="search"/>
</form>
</div>
<div id="sidebar-controls-div">
<div id="sidebar-homebutton">
<div class="sidebar-control-img" id="sidebar-homebutton-img">
</div>
</div>
<div id="Chatrooms-sidebar-button" class="sidebar-control-button">
<div class="sidebar-control-img" id="sidebar-chatroombutton-img">
</div>
</div>
<div id="avatar-sidebar-button" class="sidebar-control-button">
<div class="sidebar-control-img" id="sidebar-avatarbutton-img">
</div>
</div>

</div>


<div id="chat-rooms-div" class="main-div">
<div id="rooms">
</div>
</div>
<div id="chat-box-div" class="main-div">
<div id="chatlog-display-div">

</div>
<form id="chatform" action="">
<hr id="chat-box-div-hr">
<div id="chat-controls-div">
<input id="chat-box-div-txtinpt" class="big-txtinpt"type="text" spellcheck="false" placeholder="Message">
<input id="chat-box-div-submit" class="submit" type="submit" value="Send">
</div>
</form>
</div>
<div id="online-users-div">
<div>
<script>


var socket = io();

socket.on('connect', function(){
socket.emit('adduser', prompt("What's your name?"));
});
socket.on('updatechat', function (username, data) {
$('#chatlog-display-div').append(username + data);
});
socket.on('welcomeuser', function(data, username){
jQuery("#chatlog-display-div").append(data + username);
});
socket.on('updaterooms', function(rooms, current_room) {
$('#rooms').empty();
$.each(rooms, function(key, value) {
if(value == current_room){
$('#rooms').append('<div id="chatroom-box"><center>' + value + '<center></div><hr>');
$("#chatlog-display-div").scrollTop($("#chatlog-display-div").prop("scrollHeight"));
}
else {
$('#rooms').append('<div id="chatroom-box"><center><a id="chatroom-box-link" href="#" onclick="switchRoom(\''+value+'\')">' + value + '</a></center></div><hr>');
$("#chatlog-display-div").scrollTop($("#chatlog-display-div").prop("scrollHeight"));
}
});
});
function switchRoom(room){
socket.emit('switchRoom', room);
}




$('form').submit(function(e) {
e.preventDefault();




//right here is were i started changin it

//gets the value from the message text feild and sets it as the message var
var message = {
text : $('#chat-box-div-txtinpt').val()
}
if (message.text.trim().length !== 0) {
socket.emit('chat-message',message);
//append the message to the chatlog-display-div
$('#chat-box-div-txtinpt').focus().val('');
jQuery("#chatlog-display-div").append('<div><b>'+socket.username+':</b>&nbsp'+message.text+'</div><hr>');
$("#chatlog-display-div").scrollTop($("#chatlog-display-div").prop("scrollHeight"));
}
});
socket.on('chat-message', function (message) {
jQuery("#chatlog-display-div").append('<div><b>'+socket.name+':</b>&nbsp'+message.text+'</div><hr>');
$("#chatlog-display-div").scrollTop($("#chatlog-display-div").prop("scrollHeight"));
});

var something = document.getElementById('sidebar-homebutton');

something.style.cursor = 'pointer';
something.onclick = function() {
window.location.href = "http://billischill.ddns.net";

};

</script>





and here is my server code

index.js

var mysql = require("mysql");
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var usernames = {};
var rooms = ['General-Chat','Tech-Chat','Gamer-Chat',"BillIsChill-Underground-Chat","Programer-Chat","Hacker-Chat","Minecraft-Chat","Gta-Chat","Misc-Chat","Current-Events-Chat"];



app.get('/', function(req, res){
res.sendfile('index.html');
//res.sendfile('/login/');
});
http.listen(8080, function(){
console.log('listening on *:8080');
});

var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database: "messages"
});
io.on('connection', function (socket) {
socket.on('adduser', function(username){
socket.username = username;
socket.room = 'General-Chat';
usernames[username] = username;
socket.join('General-Chat');
socket.broadcast.to('General-Chat').emit('updatechat', '<b class="servertxt">SERVER: </b>', socket.username + ' has connected to this room' + '<hr>');
socket.emit('welcomeuser', '<b class="servertxt">SERVER:</b> Welcome ', socket.username + '<hr>');
socket.emit('updaterooms', rooms, 'room1');
});
socket.on('switchRoom', function(newroom){
socket.leave(socket.room);
socket.join(newroom);
socket.emit('updatechat', '<b class="servertxt"> SERVER </b>', 'you have connected to '+ newroom + '<hr>');
// sent message to OLD room
socket.broadcast.to(socket.room).emit('updatechat', '<b class="servertxt"> SERVER </b>', socket.username+' has left this room <hr>');
// update socket session room title
socket.room = newroom;
socket.broadcast.to(newroom).emit('updatechat', '<b class="servertxt"> SERVER </b>', socket.username+' has joined this room <hr>');
socket.emit('updaterooms', rooms, newroom);
});
console.log('a user connected');
socket.on('disconnect', function(){
// remove the username from global usernames list
delete usernames[socket.username];
// update list of users in chat, client-side
io.sockets.emit('updateusers', usernames);
socket.leave(socket.room);
});
socket.on('chat-message', function (message) {
console.log('message:', socket.username+': ' + message.text);

var insert = { roomName: socket.room, username: socket.username, message: message.text };

//puts message in db
con.query('INSERT INTO messages SET ?', insert, function(err,res){
if(err) throw err;

console.log('Last insert ID:', res.insertId);
});
//excludes "socket" from getting the emit
socket.broadcast.to(socket.room).emit("chat-message", message);
});
});


Can somone please help me i am very confused on what is happening here

Answer

Your client code has some minor bugs, I would try to make some changes,

server.js:

socket.on('chat-message', function (user, message) {
   console.log('message:', user + ': ' + message.text);
   var insert = { roomName: socket.room, username: user, message: message.text };
   //puts message in db
   con.query('INSERT INTO messages SET ?', insert, function(err,res){
    if(err) throw err;
      console.log('Last insert ID:', res.insertId);
    });
   //excludes "socket" from getting the emit
   socket.broadcast.to(socket.room).emit("chat-message", user, message);
  });

in the client:

    <html>
      <head>
        <meta name="viewport" content="width=device-width"/>
        <meta name="description" content="BillIsChill-2.0 BETA"/>
        <meta name="keywords" content="billischill,Bill,is,chill,2.0,billischill-2.0,gamer-chat,BillIsChill-Underground-Chat,BILLISCHILL"/>
        <meta name="author" content="Nik Hendricks">
        <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
        <script src="/socket.io/socket.io.js"></script>
        <title>BillIsChill-2.0</title>
        <link type="text/css"  rel="stylesheet" href="http://billischill.ddns.net/billischill-2.0/css/masterStyle.css" />
        <link type="text/css"  rel="stylesheet" href="http://billischill.ddns.net/billischill-2.0/css/animate.css" />
      </head>
      <body>
        <div id="main-header-div">
          <p id="main-header-div-text">BillIsChill-2.0<p>
            <form>
              <input id="main-header-div-search-txtinpt" class="search" placeholder="Search" name="search"/>
            </form>
        </div>
        <div id="sidebar-controls-div">
          <div id="sidebar-homebutton">
            <div class="sidebar-control-img" id="sidebar-homebutton-img">   </div>
          </div>
        <div id="Chatrooms-sidebar-button" class="sidebar-control-button">
          <div class="sidebar-control-img" id="sidebar-chatroombutton-img"></div>
        </div>
          <div id="avatar-sidebar-button" class="sidebar-control-button">
            <div class="sidebar-control-img" id="sidebar-avatarbutton-img"></div>
          </div>
        </div>
        <div id="chat-rooms-div" class="main-div">
          <div id="rooms"></div>
        </div>
        <div id="chat-box-div" class="main-div">
          <div id="chatlog-display-div"></div>
          <form id="chatform" action="">
          <hr id="chat-box-div-hr">
          <div id="chat-controls-div">
            <input id="chat-box-div-txtinpt" class="big-txtinpt"type="text" spellcheck="false" placeholder="Message">
            <input id="chat-box-div-submit" class="submit" type="submit" value="Send">
          </div>
        </form>
      </div>
      <div id="online-users-div"><div>

      <script>
        var socket = io();

        socket.on('connect', function() {
            var user = prompt("What's your name?");
            socket.username = user;
            socket.emit('adduser', user);
        });

        socket.on('updatechat', function (username, data) {
            $('#chatlog-display-div').append(username + data);
        });

        socket.on('welcomeuser', function(data, username){
            jQuery("#chatlog-display-div").append(data + username);
        });

        socket.on('updaterooms', function(rooms, current_room) {
            $('#rooms').empty();
            $.each(rooms, function(key, value) {
                if(value == current_room){
                    $('#rooms').append('<div id="chatroom-box"><center>' + value + '<center></div><hr>');
                    $("#chatlog-display-div").scrollTop($("#chatlog-display-div").prop("scrollHeight"));
                }
                else {
                    $('#rooms').append('<div id="chatroom-box"><center><a id="chatroom-box-link" href="#" onclick="switchRoom(\''+value+'\')">' + value + '</a></center></div><hr>');
                    $("#chatlog-display-div").scrollTop($("#chatlog-display-div").prop("scrollHeight"));
                }
            });
        });
        function switchRoom(room){
            socket.emit('switchRoom', room);
        }

        $('form').submit(function(e) {
          e.preventDefault();
          //right here is were i started changin it
          //gets the value from the message text feild and sets it as the    message var
          var message = {
            text : $('#chat-box-div-txtinpt').val()
          }
          if (message.text.trim().length !== 0) {
            socket.emit('chat-message', socket.username, message);
            //append the message to the chatlog-display-div
            $('#chat-box-div-txtinpt').focus().val('');
            jQuery("#chatlog-display-div").append('<div><b>'+socket.username+':</b>&nbsp'+message.text+'</div><hr>');
            $("#chatlog-display-div").scrollTop($("#chatlog-display-div").prop("scrollHeight"));
          }
        });

        socket.on('chat-message', function (user, message) {
          jQuery("#chatlog-display-div").append('<div><b>'+ user + ':</b>&nbsp'+message.text+'</div><hr>');
          $("#chatlog-display-div").scrollTop($("#chatlog-display-div").prop("scrollHeight"));
        });

      </script>
    </body>
  </html>

Please let me know if it works for you.