In the html intro to a web app for a scientific study, data is collected through forms. I added a javascript function that submits the data via the fetch API:
fetch('/prepare/', {
"method": "POST",
"redirect": 'follow',
"headers": {
"Content-Type": "application/json",
charset: "utf-8"
},
"body": data_to_send,
}).then(
response => {
if (response.redirected) {
window.location = response.url;
} else {
window.location = response.url;
}
}
)
)
This should post the request to endpoint /prepare, for which I implemented a flask function which stores the data in a database. The function returns a redirect(url_for(...)) to the endpoint /study/, where the actual research task starts.
@app.route('/prepare/', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
# Save JSON to file with task_id as the folder and uuid as the filename
#...
session_id = request.json['session_id']
pid = request.json['pid']
#redirect
return redirect(url_for('study', pid=pid, SESSION_ID=session_id), code=307)
the function for endpoint /study/ uses render_template for showing the research task.
@app.route('/study/', methods=['GET', 'POST'])
def study():
print("routed to study")
pid = request.args.get('PID')
session_id = request.args.get('SESSION_ID')
return render_template("interface.html", pid=pid ...)
The redirect to the html page rendered by /study/ does not work, the browser remains on the first page, but the url has changed with all user data key-value pairs as parameters. Interestingly, the redirect works correctly when debugging and setting two breaking points at fetch and then in the js function. Also, the terminal with the flask server showed that it actually redirected to endpoint /study/ correctly. I assume that there is a conflict between http request and js fetch api, so I set type="reset" on the html button and now it works. Before, the attribute type was not set at all. The button form is a custom button somebody else designed for the study (its a reproduction study). Is my error analysis correct? Is the solution an adequate approach or should I choose a different way?
ifstatement if you do the same thing in both cases?)at the end of the JS code.redirect: 'follow',fetch()automatically follows the redirect URL. If you want to do this yourself, you should useredirect: "manual"