1

Trying to understand how to send post requests to my backend (flask).

In my HTML I have 3 checkboxes and a submit button. My submit button returns a javascript array and I'm trying to send that javascript array to an api endpoint 'api/regions' which you can see below.

$(document).ready(function() {
    $("#loadData").click(getChecked);
});
function getChecked() {
    event.preventDefault();
    var checkboxes = $(".form-check input[type=checkbox]:checked");
    //toArray: convert checkboxes object to javascript array
    var labels = checkboxes.toArray().map(checkbox => checkbox.value);

    $.ajax({
        url: 'api/regions',
        type: "POST",
        data: JSON.stringify(labels),
        processData: false,
        contentType: "application/json; charset=UTF-8",
        success: function(response) {
            console.log(response);
        },
        error: function(error) {
            console.log(error);
        }
    });
}

In my app.py I have a route for my endpoint api:

@app.route('/api/regions', methods=['POST'])
def regions():
    regions = request.json
    with open("C:\\test.txt", 'w') as f:
        f.write(regions)

if __name__ == "__main__":
    app.run(debug=True)

I understand there is no return statement, I'm just trying to write the data I get from

regions = request.json 

to a file. "C:\test.txt"

The error I'm getting when trying to do this is 500 which doesn't give me a lot to work with. I'm not sure if what I'm missing is on the front end or back end so hopefully someone could shed some light on where I'm going wrong.

Gwith
  • 67
  • 1
  • 3
  • You might need a leading `/` in your ajax `url` parameter if you're getting a 500 error. So `'/api/regions'` instead of `'api/regions'` – Coleman Jan 24 '18 at 21:43
  • Are you seeing anything on stdout of your python process? Or in your log file? – Robᵩ Jan 24 '18 at 21:48

1 Answers1

1

From the flask documentation,

If the mimetype is application/json this will contain the parsed JSON data. Otherwise this will be None.

The key there is that .json is the parsed JSON data, not the original string. If you want to write it to a file, you'll need to convert it back to a string it first, perhaps by using json.dumps():

with open("C:\\test.txt", 'w') as f:
    f.write(json.dumps(regions))
Robᵩ
  • 163,533
  • 20
  • 239
  • 308