0

I'm trying to send some JSON data from javascript to Flask for processing. I can't get access to the json data in Flask. What do I need to change to get the data?

$.get(
    "http://127.0.0.1:5000/search",
    {"Value": "" + user_input_value + ""},
    function (data) {
        console.log(data);
    }
);
@app.route("/search")
def search():
    searchTerm = request.get_json(force=True)
    print searchTerm
    return "Whatever"
davidism
  • 121,510
  • 29
  • 395
  • 339
  • Are you using jQuery? The `$.get` seems wonky. You can check: http://stackoverflow.com/questions/6587221/send-json-data-with-jquery or post some debug info. – James King Apr 16 '15 at 23:42

1 Answers1

1

The data parameter on the jQuery get method will be encoded into a query string and appended to the url. As in

/search?Value=foo

It it's not going to be available as json on the flask side. You'd have to extract any values from the arguments dictionary like so:

 request.args.get('Value');

It's not usual to pass json as part of the query string. Usually people do a PUT or a POST and pass data on the request body. Then you can use request.get_json().

There are plenty of examples of how to put or post json to the server. I'll include an example of how to do it:

$.ajax({
                url: "/finalize_order",
                type: 'PUT',
                dataType: 'json',
                contentType: 'application/json; charset=UTF-8',
                data: JSON.stringify(Terrell.cart),
                success: function () {

                    window.location.href = '/thanks';

                }
            })
Robert Moskal
  • 21,737
  • 8
  • 62
  • 86