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>
console.log('Received');
? Or are you not seeing the message that was typed? If it is the latter the problem is hereli.innerHTML = 'msg:${data.msg}';
. To expand the placeholder (${data.msg}
) the expression should be in back ticks not single quotes.