Question:
Me and a Friend are trying to make a project, but I need to make it so when you click a button on a HTML web page, it updates a Python variable, Note: I do not know JS
I do not think this is possible using any language. (sorry)
I think you could run a POST
request to an endpoint (JS
side), and have flask modify the variable because of it (Python
side).
You can but not directly, you need to use flask anyway.
As @Firepup650 said you need to use a POST
request. You can do something simple in your python like:
@app.route('/update_variable', methods=['POST'])
def update_variable():
global your_variable
your_variable = request.form['value']
return 'Success', 200
And in HTML you make a script to work with it:
<script>
document.getElementById("myButton").onclick = function () {
fetch('/update_variable', {
method: 'POST',
headers: {
'Content-Type': 'application/www-myrepltproject',
},
body: 'value=' + Math.random(), // update the variable to a random value, just change it later.
})
};
</script>
This is just an example to give you directions.
You don’t necessarily need a POST request
<button onclick=myFunction()>Click Me!</button>
async function myFunction() {
const a = await fetch("/setvariable?data="+Math.random())
}
@app.route('/setvariable')
def set_variable():
my_variable = request.args.get('data')
return {'success': True}
Note for all these errors, try to reduce contact between python and js, as it will slow your website down. So unless you need to store in a DB or smth I recommend not even contacting the backend.
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.