I am working on a Flask project that has two pages (firstpage, secondpage). The first page has two buttons. When a user clicks on one of them, it should send a variable (variable name is value) with text to the second page. The second page should display message depending on what button the user clicked in the first page. But my program is always printing the second value even when the first button is clicked. If I declared the variable global, can I use it in the secondpage?
My html code looks kind of like this:
<form action="/firstpage" method="post">
<div><h2 >Click one button</h2></div>
<div >
<button name="btn-one" type="submit">ONE</button><br>
<button name="btn-two" type="submit">TWO</button></div>
</form>
and my Python code looks like this:
var value=""
@app.route("/firstpage", methods=["GET", "POST"])
def mymethod():
value = ""
if request.method == "POST":
if request.form.get("btn-one"):
value = "uno"
else:
request.form.get("btn-two"):
value = "dos"
print (value)
return render_template("secondpage.html")
else:
return render_template("firstpage.html")
CodePudding user response:
You can use an hidden input
field for this.
HTML:
<form action="/firstpage" method="post">
<div><h2 >Click one button</h2></div>
<input type="hidden" name="btn-pressed" >
<div >
<button name="btn-one" type="submit">ONE</button><br>
<button name="btn-two" type="submit">TWO</button></div>
</form>
Change its value depending upon the button clicked.
JavaScript:
document.addEventListener('click', (e) => {
// do not process if the clicked element is not a form button
if ( ! e.target.matches('form .btn') ) return;
// prevent form submission
e.preventDefault();
// change hidden field value
let field = document.querySelector('.hidden-field');
field.value = e.target.getAttribute('name');
// submit the form
e.target.closest('form').submit();
});
Then in Python, you can get the value through the name btn-pressed
Python:
request.form.get("btn-pressed") # to get the hidden field value
CodePudding user response:
A few syntax errors you might need to fix.
- It seems like you are mixing up different programming languages. In the first line, you entered
var value=""
. Try to remove thevar
. - Make sure your indentation is correct! Indent the block from
def mymethod():
to the bottom. - Remove the colon from the line
request.form.get("btn-two"):
. Did you meanif request.form.get("btn-two"):
instead?
Apart from that, the reason value
ends up not being either "uno" or "dos" is because of the if-statements in the code. To fix the issue, change them to:
if list(request.form)[0] == 'btn-one':
Why does this work? The request.form
looks like this:
ImmutableMultiDict(['btn-one', ''])
Transforming this into a list (i.e., getting its keys, which is either btn-one
or btn-two
) and taking the first item will tell us the button pressed.
Hope this helps :)