64

I'm having trouble getting data POSTed from jquery ajax.

$('#clickme').click( function() {
    var data = save_input(); // data

    data['_sid'] = $survey_id;  // survey_id injected from flask
    data['_uip'] = $user_ip; // user_ip injected from flask, request.remote_addr

    $.ajax({
        type : "POST",
        url : "{{ url_for('mod.load_ajax') }}",
        data: JSON.stringify(data),
        contentType: 'application/json;charset=UTF-8',
        success: function(result) {
            console.log(result);
        }
    });

    console.log(data);
});

from the code, data is a javascript object like

{
    'foo' : 'foo',
    'bar' : 'bar',
    'fo_' : 42,
}

what I'm trying to do in flask is :

@mod.route('/load_ajax', methods=["GET", "POST"])
def load_ajax():
    if request.method == "POST":
        # load _sid and _uip from posted JSON and save other data
        # but request.form is empty.
        # >>> request.form
        # ImmutableMultiDict([]) 
        return str(request.form)

see, the ajax request is made but no data is submitted. I do console.log(data) with ajax so I can see that I really have some meaningful data in data variable in jquery. but request.form in ajax view is empty. Where is my data submitted?

4
  • Change JSON.stringify(data) to data and see what happens.
    – Blender
    Feb 16, 2013 at 9:34
  • @Blender I do recieve the data. How can I receive this in JSON format?
    – thkang
    Feb 16, 2013 at 9:38
  • Have you tried request.json?
    – Blender
    Feb 16, 2013 at 9:41
  • @thkang use this as Data string: "data=" + JSON.stringify(data);.
    – 11684
    Feb 16, 2013 at 9:42

5 Answers 5

75

Try

 $.ajax({
    type : "POST",
    url : "{{ url_for('mod.load_ajax') }}",
    data: JSON.stringify(data, null, '\t'),
    contentType: 'application/json;charset=UTF-8',
    success: function(result) {
        console.log(result);
    }
});

Then from the server, you can refer to the variables in data like this :

request.json['foo']

Since the content type is specified as application/json the data is in request.json

3
  • Was pulling my hair out looking for this, request.json['foo'] did it for me. Thanks :) Apr 13, 2016 at 9:26
  • charset=UTF-8 was the trick. I was looking for it for hours.
    – akai
    May 6, 2017 at 14:34
  • yes, Flask request.data is empty when having no contentType in jquery ajax settings
    – Dan D.
    Jun 6, 2018 at 5:36
13

As per your example you are not sending a key value pair but rather assigning a JSON string to the jQuery data option. As mentioned in the comments you have to stringify your JSON, create an object with a key (which will be used to access the JSON string from flask) and then assign it to the jQuery data key.

    $.ajax({
            type : "POST",
            url : "{{ url_for('mod.load_ajax') }}",
            data: {json_str: JSON.stringify(data)},
            contentType: 'application/json;charset=UTF-8',
            success: function(result) {
                console.log(result);
            }
        });

    @mod.route('/load_ajax', methods=["GET", "POST"])
    def load_ajax():
        if request.method == "POST":
            # load _sid and _uip from posted JSON and save other data
            # but request.form is empty.
            # >>> request.form
            # ImmutableMultiDict([]) 
            return str(request.form['json_str']
     )
2

On the flask side, use:

data = request.get_json()

The variable data now has the dictionary you sent using ajax and you can now manipulate it with python

1
  • Wrote that code after staying up for 24+ hours straight. Missed a few things. I take it back. It works perfectly. My bad. Mar 1, 2019 at 6:59
1

Have you tried remove contentType? You suppose to post data to Flask.

could you try add fake data like

data:{"hello":"world"} inside ajax? just to check if the hello world arrive to request.form

0

Get Data From Ajax (Flask)

Html:

<input type="text" id="inputbox" autocomplete="off">

Js:

    $(document).ready(function(){
        $("#inputbox").on("input",function(e){
            inputbox = $("#inputbox").val();
            console.log(inputbox)
            $.ajax({
                method: "post",
                url: "/path",
                data: {inputbox},
                success:function(res){


                }
            })
        });
    });

.py :

search_value = request.form.get("text")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.