0

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?

5
  • 1
    Why are you using a fetch request and the JSON format if you collect data through forms and a completely new page is rendered after the request anyway? I would simplify things and submit a form directly to the server, thus avoiding the redirection issues. Commented Oct 20 at 12:52
  • @Detlef good point, but for the more complex study page, I need to use JS and send a complex Json, which means I still have to figure this out, even if its not necessary for the simpler start page. Commented Oct 20 at 16:44
  • What's the point of the if statement if you do the same thing in both cases? Commented Oct 20 at 21:21
  • There's an extra ) at the end of the JS code. Commented Oct 20 at 21:26
  • 1
    When you use redirect: 'follow', fetch() automatically follows the redirect URL. If you want to do this yourself, you should use redirect: "manual" Commented Oct 20 at 21:30

1 Answer 1

2

Within a form, the button type reset is responsible for resetting the form fields to their default values. See the documentation here.

A correct value for the button to submit the form would be submit.
However, based on the behavior of your code, I assume that instead of registering an event handler for the form's submit event, you are intercepting a click event of the button. In both cases, it is necessary to call preventDefault() on the event to prevent the default behavior as long as you intend to process and submit the form manually. Otherwise, the form is submitted in the conventional way. Since no attribute is specified for the method, all values ​​from form fields are appended as parameters to the URL, and a GET request is sent.

I still assume that it is not necessary to use a fetch request, even for a more complex form.
Even when using fetch, the use of JSON is not necessarily recommended, in my opinion.
I think using a FormData object makes more sense here, especially if you use a listener for the submit event. This makes querying form field values ​​much easier and maintains the format. If you still decide to transfer the data in JSON format, converting the data is also much simpler.

<form name="my-form">

    <!-- ... -->

    <button type="submit">Submit</button>
</form>

<script>
    (function() {

        document.querySelector('form[name="my-form"]')
            .addEventListener('submit', (event) => {
                event.preventDefault();
                const formData = new FormData(event.target);

                // Convert the form data to JSON or send it directly with fetch.
                // ... 

            });

    })();
</script>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.