2

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>
phaberest
  • 3,140
  • 3
  • 32
  • 40
goebels
  • 21
  • 1

1 Answers1

1

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));
      });
});
ukung
  • 411
  • 1
  • 5
  • 13