I am having some trouble using JQquery with socketio. I want the messages that are typed into the text box by the user to appear displayed as a list at the beginning of the the chat page, but am somehow failing at making that happen. Does anybody know where my mistake is?
Relevant flask code:
from flask import Flask, render_template, request, flash, session, redirect
from flask_session import Session
from flask_socketio import SocketIO, send, emit
app = Flask(__name__)
app.static_folder = "static"
app.secret_key = "My_secret_key"
app.config["SECRET KEY"] = "another_secret!"
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
socketio = SocketIO(app)
@app.route('/')
def login_form():
return render_template('index.html')
@app.route('/chat-page', methods=["POST"])
def chat_page():
username = request.form.get("user_name")
session["user"] = username
return render_template('chat-page.html', Uname=username)
@app.route("/logout")
def logout():
session.pop("user", None)
flash("You have been logged out!")
return redirect("/")
# function to send messages to the entire group
@socketio.on("message")
def handle_message(msg):
print("message: " + msg)
send(msg, broadcast=True)
if __name__ == "__main__":
socketio.run(app)
And relevant html page with jquery:
html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title> Flask Lan Chat App</title>
<link rel="stylesheet" type="text/css" href="{{url_for('static', filename='styles.css')}}">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body style="background-image: radial-gradient(circle, #4EFECD, #000000);">
<section class="hero">
<div class="hero-container">
<div class="hero-area">
<div class="hero-text">
<h1> Hello {{Uname}}! </h1>
</div>
</div>
</div>
</section>
<div class="message_container">
<div class="d-inline-flex p-2">
<div class="card" style="width: 30rem;">
<div class="card-body">
<ul id="messages">
<li>Hello World!</li>
<li>Hello World!</li>
<li>Hello World!</li>
<li>Hello World!</li>
<li>Hello World!</li>
</ul>
</div>
</div>
</div>
</div>
<!-- styling the form and buttons -->
<div class="chat_page_container">
<div class="d-inline-flex p-2">
<div class="input-group">
<span class="input-group-text">What say you?</span>
<textarea id="MyMessage" class="form-control" aria-label="With textarea"></textarea>
</div>
<div class="chat_page_container">
<div class="d-inline-flex p-2">
<button type="button" id="SendButton"class="btn btn-primary">Say it!</button>
</div>
</div>
<div class="chat_page_container">
<a href="/logout">
<button type="button" class="btn btn-warning">Logout!</button>
</a>
</div>
</div>
</div>
<!-- end of styling the form and buttons -->
</body>
<footer class="bg-dark text-center text-lg-start" style="position: absolute; bottom: 0; width: 100%;">
<!-- Copyright -->
<div class="text-center p-3" style="background-color: #1c1d25; color: white;">
© 2022 Copyright:
<a class="text-light" href="https://beatrix-droid.github.io/">Beatrice Federici</a>
</div>
<!-- Copyright -->
</footer>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js" integrity="sha512-q/dWJ3kcmjBLU4Qc47E4A9kTB4m3wuTY7vkFJDTZKjTs8jhyGQnaUrxa0Ytd0ssMZhbNua9hE+E7Qv1j+DyZwA==" crossorigin="anonymous"></script>
<script type=text/javascript">
socket.on("connect", function(){
socket.send("User has connected");
});
socket.on("message", function(msg) {
$("#messages").append("<li>" + msg + "</li>");
});
//sending a message and clearing the input box once the message has been sent
$("#SendButton").on("click", function() {
socket.send($("#MyMessage").val());
$("#MyMessage").val("");
});
});
</script>
</html>
Any help on the matter would be much appreciated!!
I can tell you that your code actually works.
You should watch out for typos and adopt code examples completely. I organized your code a bit and added the missing parts.
Have fun.
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Flask Lan Chat App</title>
<link rel="stylesheet" type="text/css" href="{{url_for('static', filename='styles.css')}}">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body style="background-image: radial-gradient(circle, #4EFECD, #000000);">
<section class="hero">
<div class="hero-container">
<div class="hero-area">
<div class="hero-text">
<h1>Hello {{Uname}}!</h1>
</div>
</div>
</div>
</section>
<div class="message_container">
<div class="d-inline-flex p-2">
<div class="card" style="width: 30rem;">
<div class="card-body">
<ul id="messages">
</ul>
</div>
</div>
</div>
</div>
<div class="chat_page_container">
<div class="d-inline-flex p-2">
<div class="input-group">
<span class="input-group-text">What say you?</span>
<textarea id="MyMessage" class="form-control" aria-label="With textarea"></textarea>
</div>
<div class="chat_page_container">
<div class="d-inline-flex p-2">
<button type="button" id="SendButton"class="btn btn-primary">Say it!</button>
</div>
</div>
<div class="chat_page_container">
<a href="/logout">
<button type="button" class="btn btn-warning">Logout!</button>
</a>
</div>
</div>
</div>
<footer class="bg-dark text-center text-lg-start" style="position: absolute; bottom: 0; width: 100%;">
<div class="text-center p-3" style="background-color: #1c1d25; color: white;">
© 2022 Copyright:
<a class="text-light" href="https://beatrix-droid.github.io/">Beatrice Federici</a>
</div>
</footer>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://cdn.socket.io/4.4.1/socket.io.min.js" integrity="sha384-fKnu0iswBIqkjxrhQCTZ7qlLHOFEgNkRmK2vaO/LbTZSXdJfAu6ewRBdwHPhBo/H" crossorigin="anonymous"></script>
<script type="text/javascript">
var socket = io();
socket.on("connect", function(){
socket.send("User has connected");
});
socket.on("message", function(msg) {
$("#messages").append("<li>" + msg + "</li>");
});
$("#SendButton").on("click", function() {
socket.send($("#MyMessage").val());
$("#MyMessage").val("");
});
</script>
</body>
</html>
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.