简体   繁体   中英

Can't get socket.emit to work on form value

I've been trying many different combinations of the code below, to figure out how to make Flask-SocketIO emit a value from a textarea. I need to use JavaScript, not JQuery. I've tested my connection to the server & the general code template with a button (it works for transmitting button datavalue), but I haven't found any solution online that works on my textarea form.

How do I put the form value inside the data, and have that value emitted back and posted in the <ul> section of the HTML page? Here is what I have:

JavaScript:

socket.on('connect', function(data){
    document.querySelector('#newmessage').onsubmit=()=>{
        const text = document.querySelector('#shoutout').value;
        socket.emit('send message', {"text": data.text});
    };
});
socket.on('list message', data =>{
    const li = document.createElement('li');
    li.innerHTML = `Message: ${data.text}`;
    document.querySelector('#messages').append(li);
});

I've also tried this for the first half of the code, putting the form value into data.text, and making it emit for every submit button click. It puts the message from textarea into the URL("/?shoutout=hello"), but it still doesn't post anything in the unordered list.

socket.on('connect', function(data){
    document.querySelectorAll('#send').forEach(button=>{
        button.onclick = ()=>{
             document.querySelector('#shoutout').value = data.text;
             socket.emit('send message', {"text": data.text});
         };
    });
});

Python/Flask:

@socketio.on("send message")
def send(data):
    text = data["text"]
    emit("list message", {"text":text}, broadcast=True)

HTML:

<body>
    <ul id="messages"></ul>
        <br>
        <form id="newmessage">
            <textarea id="shoutout" placeholder ="Type your message" rows="3"></textarea>
            <input id="send" type="submit" value="Send">
        </form>
</body>

I believe your first snippet of JS code should be:

socket.on('connect', function(data){
    document.querySelector('#newmessage').onsubmit=()=>{
        const text = document.querySelector('#shoutout').value;
        socket.emit('send message', {"text": text});  // <--- this should be text, not data.text!
    };
});

What is data.text anyway?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM