0

I'm using AJAX to send data in a POST to Flask, however the POST data that I'm getting is not something my skills can parse. Can someone help me try and understand how I can parse these variables into perhaps a list?

The data seen in Flask looks like this:

items%5B%5D=104-92923-G42LH&items%5B%5D=102-10001-CRD-P07G19&items%5B%5D=104-92925-SML-CLRH&items%5B%5D=104-92923-92R-LH&items%5B%5D=104-92924-COLTRH

When I decode it with a online decoder, then I see:

items[]=104-92923-G42LH&items[]=102-10001-CRD-P07G19&items[]=104-92925-SML-CLRH&items[]=104-92923-92R-LH&items[]=104-92924-COLTRH

My problem is, I have no idea how to parse this string into a list. I have used differnet request functions to see if I can get the data presented some other way, but still I have no luck. Currently I'm using data = request.stream.read() in my flask function to get see the data.

Also, here is my AJAX function:

$("#myForm").submit(function(e) {
            var url = "http://127.0.0.1:8080/_data";
            var result = [];
                $('.varSku').each(function () {
                result.push($(this).data("sku"));
                });
            var data1 = {items: result};
            $.ajax({
                type: "POST",
                url: url,
                dataType : "string",
                data: data1,
                success: function(data)
                {
                    console.log(data);
                }
                });
            e.preventDefault();
        });

My Flask function:

@app.route('/_data', methods=['GET','POST'])
def invoice():
    data = request.stream.read()
    print data.decode('utf8') 
    return "data"

Any help would be much appreciated.

Dusty Boshoff
  • 1,016
  • 14
  • 39

2 Answers2

0

You are looking for request.form, it automatically parses the body content into a dictionary. In your case you should use request.form["items"].

Check the documentation for more information.

Martín De la Fuente
  • 6,155
  • 4
  • 27
  • 28
0

The problem was that when sending POST data containing values that are arrays or objects, jQuery follows a PHP convention of adding brackets to the field names.

To get past it, I had to use another function called MultiDict.getlist() and therefore I had to change to request.form.getlist("items[]")

Thanks for the help @Martin

Dusty Boshoff
  • 1,016
  • 14
  • 39