My goal is an interactive html with a Python-code on the backend. In the basis, the html-page will contain a couple of sliders, and their values will be used as input for a Python-based code to returns some value(s) back to the html-page to present.
Nothing fancy, I thought. However... I want that the value of the slider is send to the Python-code immediately, and the Python-code "immediately" sends back its output ("immediately" = ASAP). For some reason, I get one of the following two working, but not both:
- The slider's value is updated immediately and its value is presented on screen. Simultaneously, I can see that the correct
Python-method is called, but no data is transferred. - The slider's value is submitted to the
Python-code and its output is returned to thehtml-page, but it requires a click on asubmit-button.
MWE:
html-page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Estimate</title>
</head>
<body>
<form method="POST">
<div class="rangeslider">
<input type="range" name="var1" min="0" max="10" value="5" class="myslider" id="slider1">
<p>
Var. 1: <span id="out1"></span>
</p>
</div>
<script>
const Http = new XMLHttpRequest();
var slide1 = document.getElementById("slider1");
var out1 = document.getElementById("out1");
slider1.oninput = function() {
out1.innerHTML = this.value;
Http.open('POST', '/output')
Http.send(out1)
}
</script>
</form>
</body>
</html>
Python-backend:
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def base():
return render_template('estimate.html', var1=5)
@app.route('/output', methods=['POST'])
def update():
# var1 = request.form['var1']
data = request.form # results in an empty dict: `ImmutableMultiDict([])`
var1 = 5 # so the return-statement does not break
print(data) # I know that this method is called, as `data` (empty dict) is printed when I change the sliders value
return render_template('estimate.html', var1=var1, output=f'Output\nVariable 1 = {var1}')
if __name__ == '__main__':
app.run(debug=True)
I do know about the option of onchange in the html-slider, but have not got it working.
I am quiet new to html and do not know much about JavaScript; I am more familiar with Python.
Hopefully anyone can help me out! I have searched around quiet a lot already, but have not found an answer to my issue.
If it matters: I am using Python 3.7, and use flask as framework.