0

I am setting up chat functionality in a Cordova project using socket.io However, I am unable to load the message at realtime.

On the client side of my Cordova app, I have written the code for the send message button as below:

$('#send').click(function() {
    if ($('#msg_inp').val()) {
        var data = {
            fromId: fromId,
            toId: toId,
            message: $('#msg_inp').val()
        }
        var child = `<div class="media"><div class="media-body media-color-right">` 
            + (data.message) + `</div></div> `

        $('#chatbox').append(child);
        $('#msg_inp').val('');
        socket.emit('chatting',data);
        }
    }
);

I am emitting the data to the server side to store the message in the database. The code on the server side is this:

socket.on('chatting', function (data) {
    userM.findSenderAndReceiver(data.fromId, data.toId, function (err, result) {
      console.log(result);
      if (err) {
          console.log(err);
          throw err;
      } else {
          userM.insertMessages(data, function (err, result) {
              if (err) {     
                  throw err;
                  console.log(err);
              }
          });

          console.log(data);
          data.chattingwith = result.from.username;
          data.chattingwithId = result.from.id;
          data.from_image_url = result.from.image_url;
          data.to_image_url = result.to.image_url;
          console.log(data);
          socket.broadcast.to(result.to.socketID).emit('chatting', data);
      }
    });
  });

On the server side after storing the message (as you can see from the above code), I am emitting the data to the receiver socketID to display the chat in the receiver's chat window at realtime.

However, I am unable to fetch the broadcasted message on the client side. I was trying it as :

socket.on('chatting',function(data){
    console.log(data) // -> This data doesn't get displayed.
});

So, how should I handle the broadcasted data from the socket to display the message at realtime?

Marwane Boudriga
  • 181
  • 1
  • 12

0 Answers0