I was doing a little project where I want to pass value of variable "x" from javascript to a pyhthon variable get_x. Can someone help me on how to do so.
index.html:
<html>
<body>
<p id="msglog"></p>
<input type="text" id="msg">
<button onclick="myFunction()">></button>
</body>
<script>
function myFunction() {
var x = document.getElementById("msg").value;
document.getElementById("msglog").innerHTML = x;
return x
}
</script>
</html>
main.py:
from flask import Flask, render_template
app = Flask(__name__,template_folder='',static_folder='')
@app.route("/")
def mainpage():
return render_template('/index.html')
app.run(host='0.0.0.0')
You must send a request to your flask application. For that you need an AJAX request. e.g. shown in this post: How to GET data in Flask from AJAX post
I also recommend you to use jQuery like this example from https://flask.palletsprojects.com/en/2.0.x/patterns/jquery/
Python:
from flask import Flask, jsonify, render_template, request
app = Flask(__name__)
@app.route('/_add_numbers')
def add_numbers():
a = request.args.get('a', 0, type=int)
b = request.args.get('b', 0, type=int)
return jsonify(result=a + b)
@app.route('/')
def index():
return render_template('index.html')
Javascript/jQuery
<script>
$(function() {
$('a#calculate').bind('click', function() {
$.getJSON($SCRIPT_ROOT + '/_add_numbers', {
a: $('input[name="a"]').val(),
b: $('input[name="b"]').val()
}, function(data) {
$("#result").text(data.result);
});
return false;
});
});
</script>
<h1>jQuery Example</h1>
<p><input type=text size=5 name=a> +
<input type=text size=5 name=b> =
<span id=result>?</span>
<p><a href=# id=calculate>calculate server side</a>