-2

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'".

Since I intend to pass only one variable to the Python file, 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>
ggorlen
  • 44,755
  • 7
  • 76
  • 106

2 Answers2

0

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.

Christoph
  • 647
  • 5
  • 18
0

Terminology tips:

  • Think less in terms of "files" and more in terms of "applications". Your code is stored as text in a file, but when the Python or JS runtime executes the code, it runs as an application in memory, not on disk (where files live).
  • The client and the server don't share variables. In our case, they share raw data via HTTP requests. A client serializes data (possibly stored in variables) into a raw byte sequence, creates a request with a payload and sends it over the network. The server deserializes the data and creates variable(s) to store the values in the memory reserved for its process. After processing the data, the server sends a response, which can also have a data payload.

This may seem overly pedantic, but having a clear mental picture of the client-server architecture is important to be able to ask the right questions and implement features easily.


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 listener to the form submission, call event.preventDefault() inside the handler, then use jQuery to post the data. Here's an example.

Either way, either approach is about as short as it gets. Libraries like htmx exist that create an illusion of simplicity, but there's a learning curve and potential for further misunderstandings when failures arise, so I'd stick to the basics for now--you can get surprisingly far with them.

ggorlen
  • 44,755
  • 7
  • 76
  • 106