V
V
Vadim Stepanenko2018-03-26 23:17:29
Node.js
Vadim Stepanenko, 2018-03-26 23:17:29

Why doesn't socket.io transfer work?

Hello!
I started to study socket.io, I ran into this problem:
The site has a form (input text + button). The user enters text and sends a message to the chat
Using PHP, user data (login, link to avu, id) is substituted into the script code.
The code on the client is:

spoiler
..........

// Отправка сообщения при клике
$('#send-btn').click(function() {
  var message = $('#message').val();
  var username = '<?=$user['personaname']?>'; 
  var avatar = '<?=$user['avatarmedium']?>';
  $('#message').val('');

  socket.emit('new message', (username, message, avatar));
});

// Получаем сообщения (для начала пытаюсь просто в консоль вывести значения)
socket.on('new message', (username, message, avatar) => {
  console.log('Message from: ' + username);
  console.log('Message: ' + message);
  console.log('Ava: ' + avatar);
  console.log('_____________________');
});

..........

Server code:
spoiler
socket.on('new message', function (username, message, avatar) {
  console.log('new message');

  io.sockets.emit('new message', (username, message, avatar));
});

But for some reason it gives the following in the console:
spoiler

Message from: null
Message: undefined
Ava: undefined
_____________________

Tell me what am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
DanielParokonnyy, 2018-03-27
@DanielParokonnyy

Yes, because only an object with variables (one parameter) should be transferred. Just pass in an object (you can call it pocket) and set the object's properties to username, message, avatar. And to get values ​​like this: pocket.username ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question