Why only first item from list created with jQuery is sent through Ajax

Issue

I have a list that I created with jQuery as follows:

        pros=[];
        cons=[];
        $.each($(".pro-item"), function(){
            pros.push($(this).html())
        })
        $.each($(".con-item"), function(){
            cons.push($(this).html())
        })

Now I want to pass it to server for processing, so I use Ajax:

$.ajax({
        data: {
            pros: pros,
            cons: cons,
        },
        type: 'POST',
        dataType: "json",
        traditional: true,
        url: '/pro_con_list',
        success: function(data){
            console.log("Ajax call successful")
        }
})

But when server(flask/python) receives it and I print the resulting data as such:

pros = request.form.get("pros")
print(pros)
print(request.form.get("cons"))

It only prints the first item of the JS list that was sent. I console.log both pros and cons lists and it shows full lists:

(3) ["foo", "foo bar", "foo bar buz"]
(3) ["buz", "buz bar", "buz bar foo"]

And this is what python prints it received:

foo
buz

I assume I am not sending the the list properly, but the seemed to be the only way working and not printing None.

Solution

Try request.form.getlist("pros")

To tease that out of the documentation, start at https://flask.palletsprojects.com/en/1.1.x/api/#flask.Request.form and drill down through ImmutableMultiDict to MultiDict, which is where most of the methods that form responds to are documented.

Answered By – Dave W. Smith

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published