Search code examples
javascriptpythonajaxflask

Having trouble with sending data from JavaScript to Python Flask


I am running a simple setup where a string should be sent to my Flask app via Ajax, but I am receiving Error code 400: Bad request.

JavaScript code:

headers = {
    'Content-type':'application/json',
    'Accept':'application/json'
}

function send(){
    const line = textbox.value;
    $.ajax({
        type: "POST",
        url: "/send",
        data: line,
        headers: headers,
    });
}

Python code:

@app.route("/send", methods=["POST"])
def print_data():
    data = json.load(request.get_json().get("data"))
    main.FileMan.post_data(str(data))

Where the last line is where I call a Python file called main and output the data in a text document.


Solution

  • I'm not sure what the structure of textbox.value is but you need to stringify your data before sending it like this:

    headers = {
        'Content-type':'application/json',
        'Accept':'application/json'
    }
    
    function send(){
        const line = textbox.value;
        $.ajax({
            type: "POST",
            url: "/send",
            data: JSON.stringify(line),
            headers: headers,
        });
    }
    

    And in your Flask code, you are already using request.get_json() to parse the JSON data so you need to remove json.load() since you are trying to parse data from a POST request and not from a file. Your Flask code should look like this:

    @app.route("/send", methods=["POST"])
    def print_data():
        data = request.get_json().get("data")
        main.FileMan.post_data(str(data))
    }