Search code examples
javascriptflaskxmlhttprequestform-datarequest.form

Submitting multiple forms to Flask (400 BAD REQUEST)


I'm currently learning Flask.

I've got multiple forms in my HTML and I want to send the form data to my backend in Flask. I've managed to successfully send over the data from a single form, but I'm having trouble with getting it to submit multiple forms at once.

Here's my JavaScript on getting the form data and appending each form:

function createUser() {
  var xhr = new XMLHttpRequest();
  var formData = new FormData()
  formData.append("userID", document.getElementById("newUserID").value);
  formData.append("userEmail", document.getElementById("newUserEmail").value);
  formData.append("userFirstName", document.getElementById("newUserFirstName").value);
  formData.append("userLastName", document.getElementById("newUserLastName").value);
  formData.append("userAvatar", document.getElementById("newUserAvatar").value);

  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status < 300) {
      alert(xhr.responseText)
    }
  }
  xhr.open("POST", "api/add", true);
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
  xhr.send(formData);
}

Here's my Flask:

@app.route('/api/add', methods = ['GET', 'POST'])
def post_user():
  if request.method == "POST":
    user = (request.form['UserID'],
            request.form['UserEmail'],
            request.form['UserFirstName'],
            request.form['UserLastName'],
            request.form['UserAvatar'])
  else:
    return render_template('users.html')
  user.append(user_list)

If I were to guess where I've gone wrong, it would be the formData.

Any help or pointers would be great. Thanks!


Solution

  • When you get 400 Bad Request, it's often because some integral logic like an incorrect key being used for the request object. In your case, the cases do not match between the backend and the XHR request.

    I'd also recommend using request.form.get(value) since it will return None rather than raise an error like 400 Bad Request.