Access a JSON data from python in JavaScript

Viewed 37

I have a flask URL called register, where I collect the users's input and process them like so:

@app.route("/register", methods=["POST"])
@login_required
def register_post():
    email = request.values.get("email")
    username = request.values.get("username")
    company_name = request.values.get("company_name")
    password = request.values.get("password")
    confirm_password = request.values.get("confirm_password")
    messages = register(email, username, password, confirm_password, company_name)
    success_message = (
        "Thank you for registering with us. We will get back to you shortly."
    )
    print("request values: ", request.values)
    print("messages: ", messages)
    if (len(messages) == 1) and (messages[0] == success_message):
        return jsonify({"code": 200, "message": messages[0]})
    else:
        return jsonify({"code": 400, "message": messages})

Based on the messages, I would like to display the messages with a native browser pop-up. I am trying to access that JSON data in Javascript like so:

$.ajax({
    url: "/register",
    type: "POST",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (json) {
        alert(json);
    },
    error: function (e) {
        alert(e);
    }
});

I get the JSON object in the browser but it doesn't alert anything in the browser. what could I be doing wrong?

Screenshot of the dev tools below: enter image description here

Network tab enter image description here

1 Answers

You have some code which is navigating to /register so the JavaScript making the Ajax request is irrelevant.

Presumably you are submitting a form with action="/register".

If you want to perform the Ajax request instead then you need:

  • An event handler
  • To prevent the default behaviour of submitting a form
$('form').on('submit', evt => {
    evt.preventDefault();
    //... gather your data for the request body
    $.ajax(...);
});

Note that your existing JS is missing the data property from the object you pass to ajax. You'll need to populate that with the data you are sending.

Related