I can't seem to get a message sent to the server and then added to my html document as a list item using socketio.
I get to type in a message and click the send button, but then nothing happens.
As far as I understand I'm: 1- Emitting a new message from my javascript client-side, 2- Receiving and announcing it from my application.py server-side, 3- Adding it to my html as a new list item, again client-side.
What am I missing here? I'm pasting the relevant parts of my code below, html, js and python, in case someone sees it. Many thanks.
chat.html - Here I have a form to send new messages:
<h3>Send a message</h3>
<form id="message_form">
<input id="message" type="text" placeholder="Write a Message">
<button id="send_btn" type="button">Send</button>
</form>
<hr>
<h3>Messages</h3>
<ul id="messages">
</ul>
chat.js - Here I am emitting a 'submit message' event when the form's button is pressed. Also, when an 'announce message' event is received, I am adding a new list element to mu unordered list:
document.addEventListener('DOMConentLoaded', () => {
// Connect to websocket.
var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
// When connected, configure buttons.
socket.on('connect', () => {
// Button emits a 'submit message' event.
document.querySelector('#message_form').onsubmit = () => {
// Save message and emit
const message = document.querySelector('#message').value;
socket.emit('submit message', {'message': message});
// Clear input.
document.querySelector('#message').value = '';
// Stop form from submitting.
return false;
};
});
// When a new message is announced, populate list of messages.
socket.on('announce message', data => {
const li = document.createElement('li');
li.innerHTML = data.message;
document.querySelector('#messages').append(li);
});
});
application.py - Here, I receive the 'submit message' event and I emit an 'announce message' event:
@socketio.on("submit message")
def msg(data):
""" Receive message and broadcast """
message = data["message"]
emit("announce message", {'message': message}, broadcast=True)
Following the instructions on lecture 5 with the 'votes' examples and searching on Internet, I still don't understand what am I missing.
Any help would be most appreciated. Thank you for your time in advance.