Search code examples
pythonhtmljsonflaskdeployment

Parsing variable from HTML/JS to Python with Flask always returns None


I'm trying to parse a string variable, "articlename" to my main Flask Python script from HTML (with JS). However, all it returns is None. How can I fix this?

HTML/JS:

    <p>
        <button id="likebutton" onclick="likePost()">
            <img class="likebuttonimg" src="static/images/clearlike.png" id = image>
        </button>
    </p>
    <p>
    {{likes}} likes
    {{views}} views
    </p>

    <script>
        let data = new FormData()
        data.append("name", "sketchystrats")

        document.getElementById("likebutton").onclick = function () {
            fetch('/tracklikes', {
                method: 'POST',
                headers: {'name': 'sketchystrats'},
                body: JSON.stringify(data),
            })
        };
    </script>

Relevant section of Python:

@app.route("/tracklikes", methods=['POST'])
def tracklikes():
    print("TrackLikes activated")
    articlename = request.form.get('data')
    print(str(articlename))

Then it does some database stuff that isn't super relevant. For note, I don't know what I'm doing when it comes to Javascript.


Solution

  • You must decide whether you want to send JSON format or form data.
    Your endpoint expects a form, so remove JSON.stringify(...) and send the FormData object directly. Specifying the header is also not necessary.

    let data = new FormData()
    data.append('name', 'sketchystrats')
    
    document.getElementById('likebutton').onclick = function () {
        fetch('/tracklikes', {
            method: 'POST',
            body: data,
        });
    };
    

    On the server side, the input must be queried based on the name under which you added the data to the FormData object. In your case this corresponds to name, not data.
    Don't forget that an endpoint requires a return value, otherwise an error will be thrown.

    @app.post('/tracklikes')
    def tracklikes():
        articlename = request.form.get('name')
        print(articlename)
        return ''