0

On button click, the message 'door' should appear on the console but it isn't.

Client code :

<button type="button" onClick = "doorClicked()">Door</button>

function doorClicked(){
        socket.emit('door', function(data){
            socket.send("Door");
        });
}

Server side :
io.sockets.on('connection', function(socket){
socket.on('door', function(data){
        console.log('Door');
    });
}
Divesh
  • 1
  • 1
  • 5
  • On the client, don't pass a function - instead pass the payload. You don't need to call send. – tariksbl Jul 10 '15 at 01:04
  • just passing the payload will require changes on the server-side as well, and when I changed the server-side code as follows : socket.on('door', io.sockets.emit('doorEvent', {msg: data}) ); I got the following error : Reference Error : Data is not defined ...Tried searching for a sloution for the same, but no luck @tariksbl – Divesh Jul 10 '15 at 02:15

2 Answers2

0

You should try this on doorClicked function:

function doorClicked(){
    socket.emit('door');}

You don't need any data to emit. Because you are consoling out the string 'Door'. So, your server side code should be like this,

    Server side :
io.sockets.on('connection', function(socket){
socket.on('door', function(){
        console.log('Door');
    });
}
mg52
  • 116
  • 1
  • 7
0

Ok, so the problem is solved and it was in the part of the code which I haven't mentioned in my question, and I'm extremely sorry for that.

On the client-side code, I had the button along with other button in the same form, and whenever I clicked the other button, the event was notified. So I tried placing the buttons on different tags in my client-side HTML code and it worked fine.

P.S. I didn't include the entire code earlier because I was expecting the error to be in the part of the code that had to deal with socket.io since I was new at it.

Divesh
  • 1
  • 1
  • 5