My current problem is that there are two browsers (two users). Once both of them are connected, they could do a certain socket event which is a friends Request but not both at the same time. Always need to refresh one of the user's page.
Illustratively
When a user click this button
the navbar glyphicon will be incremented by 1
Serverside event
io.on('connection', function(socket){
// Everytime user is connected, I will do some Database operation to store the socketId, it will look something like this
user.socketId = socket.id; // For simplicity.
console.log(socket.request.user.username); // is using passport-socket.io library
socket.on('friendsRequest', function(data) {
// Got these two datas from input hidden on html by using Jquery
var socketId = data.socketId;
var userId = data.userId;
socket.to(socketId).emit('friendsRequest', socket.request.user);
console.log("Successful" + " from " + socket.request.user.username);
});
The weird thing is , on the serverside it is always showing console.log("Successful" + " from " + socket.request.user.username);
meaning if click the button on both User's browser it will show correctly
"Successful from UserA"
"Successful from UserB"
But the problem is on the clientside, the targeted html never changed, it always one of the browser navbar's glyphicon will be incremented
Here's the code on the client side
// This event will send the targeted data like socketId and userId back to the server
$(document).on('click', "#addFriend", function(e){
e.preventDefault();
var userId = $('#userId').val();
var socketId = $('#socketId').val();
socket.emit('friendsRequest', {
userId: userId,
socketId: socketId
});
});
// Once the server has done doing his job, this event will listen.
socket.on('friendsRequest', function(data) {
var totalRequests = parseInt($('#totalRequests').html());
console.log(totalRequests);
totalRequests += 1;
$('#totalRequests').html(totalRequests);
$('#friendsRequested').append('<li>' + data + '</li>');
});
The main problem is on the clientside socket.on('friendsRequest');
It only works of one of the browsers but not both at the same time when I fired the friendsRequest event
Need someone with socket.io expertise to explain to me why it doesn't work both ways. As to my logic it is supposed to work.
html
<input type="hidden" name="socketId" id="socketId" value="ValueOftheSocketId" />
<button type="submit" id="addFriend" class="btn btn-default">Add Friend</button>