Let's see and understand the way a client/server application work:
From the user's browser:
- the user enter a value in a form;
- the user submit the form;
- the form data is posted to the server and wait for the response.
On the server:
- the server get the HTTP request and decode it;
- the URL is translated into a "route";
- the server call the function or method attached to the route;
- the function do it's job and must return a HTTP response (data + status code);
- the response (more often a HTML page) is sent back to the browser.
On the user's browser:
- the browser render the HTML page (or other kind of data);
- the user can then continue it's browsing.
… and the loop is done.
From the user's browser:
What you want is a way to register the user's change to database.
To do that, you can use a classic HTML form or an Ajax request. Since your are using JavaScript, an Ajax request is the best way to do that. For instance, you can use jQuery.post to do that:
Here is a draft:
<script type="text/javascript" charset="utf-8">
function change_color(t) {
var url = "/route/to/change_color";
var data = {color: $('#chat-color').val()};
$.post(url, data);
}
</script>
This code get the value of the input field which id is #chat-color and post it to the URL "/route/to/change_color".
Of course, you need th change your HTML form like this to add the #chat-color id:
<div>
Check your color in chat:
<input id="chat-color" type="color" value="{{ user.text_color_in_chat }}" onchange="change_color(this);">
</div>
On the server:
You need to define a function for the route "/route/to/change_color".
The function could be:
import re
from flask import request
@app.route('/route/to/change_color', methods=['POST'])
def change_color():
new_color = request.form['color']
if re.match(r'^#[0-9a-f]{6,6}$', new_color):
self.text_color_in_chat = new_color
db.session.add(self)
...
...
Here is a small solution which use a global variable instead of a database (to keep it simple):
# coding: utf8
import json
import re
import textwrap
from flask import Flask
from flask import request
app = Flask(__name__)
text_color_in_chat = "#000000"
@app.route('/')
def hello_world():
content = textwrap.dedent("""\
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript" charset="utf-8">
function change_color(t) {
var url = "/route/to/change_color";
var data = {color: $('#chat-color').val()};
$.post(url, data);
}
</script>
<div>
Check your color in chat:
<input id="chat-color" type="color" value="<color>" onchange="change_color(this);">
</div>
""")
return content.replace("<color>", text_color_in_chat)
@app.route('/route/to/change_color', methods=['POST'])
def change_color():
new_color = request.form['color']
if re.match(r'^#[0-9a-f]{6,6}$', new_color):
global text_color_in_chat
text_color_in_chat = new_color
return json.dumps({'change_color': "OK"})
return json.dumps({'change_color': "Invalid color"})
if __name__ == '__main__':
app.run(debug=True)