I am submitting 2 forms with one button using JavaScript. But when I am trying to access it using request.form in flask, it is only showing the 2nd form(the last submitted form). How can I access both forms in the backend? Will I have to use ajax? I am new to JS, flask, HTML. Thanks!
Here's my HTML code:
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form method ="post" id="f1" name = "form1" action="{{url_for('process')}}">
<input type="text" name = "name">
</form>
<form method ="post" id="f2" name="form2" action="{{url_for('process')}}">
<input type="text" name = "name">
</form>
<button type="button" value="submit" onclick="sub()">sub
</button>
</body>
<script>
function sub(){
document.getElementById("f1").submit();
document.getElementById("f2").submit();
}
</script>
</html>
Here's my flask code:
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('forms.html')
@app.route('/processing', methods=['POST',"GET"])
def process():
print(request.form) #This only prints ImmutableMultiDict([('name', 'name submitted by f2')])
return "processsed"
if '__main__' == __name__:
app.run(debug=True)
CodePudding user response:
Use form data and send.
Not tested, if there's any problem please comment.
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form method ="post" id="f1" name = "form1" action="{{url_for('process')}}">
<input type="text" name = "name">
</form>
<form method ="post" id="f2" name="form2" action="{{url_for('process')}}">
<input type="text" name = "name">
</form>
<button type="button" value="submit" onclick="sub()">sub
</button>
</body>
<script>
async function sub() {
var form = new XMLHttpRequest();
form.open(document.getElementById("f1").method, document.getElementById("f1").action);
var p = new Promise(r => {
form.onreadystatechange = function() {
if (form.readyState === XMLHttpRequest.DONE && form.status === 200) r();
}
});
form.send(new FormData(document.getElementById("f1")));
await p;
form = new XMLHttpRequest();
form.open(document.getElementById("f2").method, document.getElementById("f2").action);
p = new Promise(r => {
form.onreadystatechange = function() {
if (form.readyState === XMLHttpRequest.DONE && form.status === 200) r();
}
});
form.send(new FormData(document.getElementById("f2")));
await p;
window.location.reload();
}
</script>
</html>