0

I have a problem regarding passing posted messages into the proper field and presenting them to the user. The app is supposed to transfer the text submitted in "messenger" into the "messages" so to let users chat with each other. I have been trying to find the source of the issue by myself but I failed. Probably the message typed is not send to Python's script and back to JavaScript's code but I honestly do not know where have I commited the mistake which prevent the app from doingo so.

My codes are presented below:

JavaScript

document.addEventListener('DOMContentLoaded', function () {
var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
var my_storage = window.localStorage;
socket.on('connect', () => {

    document.querySelector('#messenger').onsubmit = function () {
        msg = document.querySelector("#message").value;
        socket.emit('message', { 'msg': msg});
        document.querySelector("#message").value = '';

    };
socket.on('message', data => {
            console.log('Received');
            const li = document.createElement('li');
            li.innerHTML = 'msg:${data.msg}';
            document.querySelector("#messages").append(li);
        });
    });

Python:

@socketio.on("message")
def sendMessage(json):
   #timestamp
  msg_time=time.ctime(time.time())
  msg_data={"msg":json["msg"], "my_time":msg_time}
  my_messages.append(msg_data)
  print("message sent")
  emit("message", msg_data, broadcast=True)

if __name__ == '__main__':
  socketio.run(app)

HTML:

 <div id="chat-field" class="col-md-11">
  <ul id="messages"></ul>
  </div> 
  <div class="row">

  <form id="messenger">

  <input id="message" type="text"  placeholder="Enter your message">
  <input type="submit">
  </div>
4
  • Small clarification please. Are you not receiving the message (ie do not see console.log('Received');? Or are you not seeing the message that was typed? If it is the latter the problem is here li.innerHTML = 'msg:${data.msg}';. To expand the placeholder (${data.msg}) the expression should be in back ticks not single quotes. – DinoCoderSaurus Feb 23 '19 at 15:43
  • Dear @DinoCoderSaurus, I neither receive the message nor see the typed text. – Krystian Feb 24 '19 at 22:11
  • Dear @DinoCoderSaurus, thank to Your advice the message is passed into the window. Now, the problem is that it disappears shortly after. – Krystian Feb 24 '19 at 22:17
  • @DinoCoderSaurus I've realized where the problem was - the form was submitted and so the page was reloaded after submission. After slight code alterations everything works fine :) – Krystian Feb 24 '19 at 22:51

You must log in to answer this question.

Browse other questions tagged .