demathieu
demathieu

Reputation: 479

socket IO send form data from client to server

I'm trying to send a simple message from a form to my server using socket.io. Sadly enough this is failing, I know the client has a connection with the server, but it does not appear to receive the messages.

Could someone explain to me why my code is failing?

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');
});

http.listen(8001, function(){
  console.log('listening on *:8001');
});

io.on('connection', function(socket){
  console.log('connection is er');
  socket.on('message', function(msg){
    console.log('test');
    console.log('message: ' + msg);
  });
});

index.html :

<html>
   <body>
    <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('message', $('#Input').val());
        //socket.emit('message', "Input");
        //$('#Input').val('');
        return false;
      });
    </script>
    <form id = "form" action = "">
      Input: <input type="text" id="Input"><br>
      <input type="submit" value="Submit">
    </form>
   </body>
</html>

Upvotes: 4

Views: 14853

Answers (4)

KUMAR SAURAV
KUMAR SAURAV

Reputation: 331

The default action of form is to refresh the page. So,

form.addEventListener("submit",(e)=>{
    e.preventDefault();
    //Rest of the code
});

This will prevent the default action of the form

Upvotes: 0

Revilo
Revilo

Reputation: 31

Thanks Connor D

That was definitely the solution.

for thoses who have the same problem, you can check javascript error with F12 on Chrome then Console. If it says :

Uncaught ReferenceError: $ is not defined

You probably miss this import :

script src="http://code.jquery.com/jquery-1.11.1.js"></script>

Upvotes: 3

Connor Dooley
Connor Dooley

Reputation: 389

Try wrapping this code

$('#form').submit(function(){
    socket.emit('message', $('#Input').val());
    //socket.emit('message', "Input");
    //$('#Input').val('');
    return false;
  });

in a $(document).ready(function(){/*code here*/});

Upvotes: 2

galethil
galethil

Reputation: 1016

It looks like your client is using socket.io JS file from socket.io website but you didn't specified host and port of YOUR server.

Check out the documentation http://socket.io/docs/#using-with-the-express-framework you need to do something like

var socket = io.connect('http://localhost:8001');

Upvotes: 1

Related Questions