Issue
html code :
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
socket.on('connect', () => {
const selection = document.querySelector('#text').value;
socket.emit('submit value', {'selection':selection});
});
socket.on('submit text', data => {
const li = document.createElement('li');
li.innerHTML = `msg: ${data.selection}`;
document.querySelector('#list').append(li);
});
});
</script>
<title>chat room</title>
</head>
<body>
<h1 style="font-family:verdana; font-style:italic;">Chat room!!!</h1>
<ul id="list">
</ul>
<hr>
<form id="chat">
<input id="text" autocomplete="off" autofocus placeholder="enter text">
<input type="submit">
</form>
</body>
python code :
import os
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
app = Flask(__name__)
app.config["SECRET_KEY"] = os.getenv("SECRET_KEY")
socketio = SocketIO(app)
@app.route("/")
def index():
return render_template("index.html")
@socketio.on("submit value")
def chatting(data):
selection=data["selection"]
print(selection)
emit("submit text", {"selection":selection}, broadcast=True)
Hello everyone, I'm trying to make a 'chat room' for my course project and, above is my code. So when I submit my form nothing happens, I don't get any output. It Seems my entered text didn't go to the server. Please help me solve this issue. Thank you.
Solution
You don't currently have a handler for the form submit in your javascript. Just add this inside document.addEventListener
:
$('form#chat').submit(function(event) {
const selection = document.getElementById('text').value;
socket.emit('submit value', {'selection':selection});
return false;
});
Answered By - jignatius
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.