Reputation: 93
I'm working on this simple tic-tac-toe app and whenever a player hits a button it will trigger the function markTheCell(button) passing the button's id. This function then emits the player which is string value and the button id to the server. I put console log in the client page to see whether a valid value is being passed and it is. But when I tried to log it in the server the value of the player become object Object and the button id is undefined. I don't know if I failed how to put and use the parameters correctly. Hope someone lend a help because I'm stuck with this.
index.html
<body>
<div class="col-lg-4"></div>
<div class="col-lg-4 jumbotron">
<h4>You are player <span id="name"></span></h4>
<button id="one" onclick="markTheCell(this.id)" class="btn btn-default"></button>
<button class="btn btn-default"></button>
<button class="btn btn-default"></button></br>
<button class="btn btn-default"></button>
<button class="btn btn-default"></button>
<button class="btn btn-default"></button></br>
<button class="btn btn-default"></button>
<button class="btn btn-default"></button>
<button class="btn btn-default"></button>
</div>
<div class="col-lg-4"></div>
</div>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
var player = "";
$(document).ready(function () {
socket.on('player', function (playerNo) {
player = playerNo;
$('#name').text(playerNo);
});
socket.on('hitAMark', function (player, button) {
console.log("in client hit a mark player "+ player);
console.log("in client hit a mark button "+ button);
$(button).text(player);
});
})
function markTheCell(button) {
socket.emit('mark', {player,button });
console.log("in markTheCell client hit a mark player "+ player);
console.log("in markTheCell client hit a mark button "+ button);
}
</script>
</body>
index.js
var player = 0;
io.on('connection', function(socket){
if(player==0){
player++;
socket.emit('player', "X");
console.log("Player "+ player +" is connected");
}else if(player==1){
player++;
socket.emit('player', "O");
console.log("Player "+ player +" is connected");
}
socket.on('disconnect', function(){
console.log('A user is disconnected');
});
socket.on('mark', function(player, button){
console.log("in server hit a mark button "+ player);
console.log("in server hit a mark player "+button);
io.emit('hitAMark', {player,button});
});
});
http.listen(3000, function(){
console.log('Server is listening on port 3000!');
});
The screenshot of the console in browser and cmd:
Upvotes: 0
Views: 1257
Reputation: 187
try emitting {player:player,button:button}
instead of {player,button}
. May be it can work.
Upvotes: 1