Home > Mobile >  Passing array of selected values from select2 multiple to Flask
Passing array of selected values from select2 multiple to Flask

Time:10-06

html:

<form method="POST">
    <span id="searchProject" style="width: 50%"></span>
    <span id="searchHR" style="width: 50%"></span>
</form>

jquery:

function loader() {
    var selectedValues = [];
    $("#searchHR:selected").each(function(){
        selectedValues.push($(this).val());
    });
    console.log(selectedValues);

    $.getJSON('/query_values', {
        selected_HR: selectedValues,
        selected_project: $('#searchProject').val(),
    })
}

flask:

@app.route('/query_values', methods=['POST'])
def query_values():
    project = request.args.get('selected_project', type=str)
    hr = request.args.get('selected_HR')
    print(hr)
    return project, hr

console.log(selectedValues): [A0, A10]

GET /query_values?selected_HR[0][name]=0&selected_HR[0][value]=A0&selected_HR[1][name]=1selected_HR[1][value]=A10&selected_project=Catch123 HTTP/1.1

print(hr): None

Why is the value of hr returning None? I have tried to serialize (selectedValues) and it returns undefined undefined.

CodePudding user response:

Figured it out. Had to add JSON.stringify to selectedValues.

$.getJSON('/query_values', {
    selected_HR: JSON.stringify(selectedValues),
    selected_project: $('#searchProject').val(),
})

CodePudding user response:

Encode array parameters with traditional style.

$.getJSON({
    url:'/query_values', 
    data:{
        selected_HR: selectedValues,
        selected_project: $('#searchProject').val(),
    },
    traditional:true // important !!
});

Get array params with getlist method

@app.route('/query_values', methods=['POST'])
def query_values():
    project = request.args.get('selected_project', type=str)
    hr = request.args.getlist('selected_HR')
    print(hr)
    return project, hr
  • Related