Home > Net >  How to pass JavaScript variable to Flask?
How to pass JavaScript variable to Flask?

Time:04-07

So I want to access the javascript variable file in the app.py file but it's giving me a bad request which says "Did not attempt to load JSON data because the request Content-Type was not 'application/json'". I am super new to flask, help me out. And also since I intend to pass only one variable to the python file so is there not some other shorter method to do so other than using JSON?

@app.route("/", methods=["GET", "POST"])
def index():
    if "stop" in request.form:
        data = {}
        data["file"] = request.json("file")
        print(data, file=sys.stderr)
    return render_template("index.html")
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="./static/styles/style.css">
    <title>Title</title>
</head>
<body>
<form method="post">
    <input type="submit" name="start" onclick="startRec" value="start"/>
    <input type="submit" name="stop" value="stop"/>
</form>
<script>
        const startRec = () => {
            var file = {"file" : "whatever"};
            $.ajax({
            url : "/",
            type : "POST",
            contentType : "application/json",
            data : JSON.stringify(file)
            })
            .done(function(res){
            console.log(res)
            });
    }
</script>
</body>
</html>

CodePudding user response:

You submit the form and also do your ajax call at same time.

Use a Form or an Ajax function to send data. And not both.

Remove your form, use normal buttons with onclick mapped to your ajax function.

CodePudding user response:

Terminology tip: "variables" aren't exactly what you're passing here. It's not possible to pass variables from the client to the server. A request serializes data (possibly stored in a variable(s) on the client process) into a raw byte sequence, creates a request with a payload and sends it over the wire. The server deserializes the data on the receiving end, creating variable(s) to store the data.

Now, there are multiple ways to send data. You can use JSON or form data to format a POST payload, but it looks like you're conflating the two.

if "stop" in request.form: deals with the form, but data["file"] = request.json("file") deals with JSON. When the form is submitted, it POSTs the form data to the route /, and "stop" is indeed in request.form. But the request type isn't JSON, it's form data, hence the error once you attempt to access request.json.

You have two options:

  1. Use form data triggered by the HTML. Put whatever you want the payload to be entirely within the form. No JS will be involved. Here's an example.
  2. Use an asynchronous JS request. Remove the form method="post", attach an event listner to the form submission, call event.preventDefault() inside the handler, then use jQuery to post the data. Here's an example.
  • Related