[Flask][Ajax] How to send and get multiple checkbox values

  ajax, flask, javascript, python

I’m trying to submit multiple checkbox values using AJAX and then add checked items to div element. Because a number of checkbox varies depending on cases, I don’t know a way to send and get such a multiple data. In HTML code below, the length of the list person_name changes depending on users.

HTML:

 {% for name in person_names %}
      <label><input type="checkbox" name="check" value="{{name}}">{{name}}</label>
 {% endfor %}
 <a href=# id="add">Add</a>                                        

 <div id="names">
      Your checked names are: 
      {% for ckname in cknames%}
      <p>{{ckname}}</p>
      {%endfor%}
 </div>

Javascript:

$('a#add').bind('click',function(){
$.ajax({
    url: "/regist",
    type: "GET",
    contentType: 'application/json;charset=UTF-8',
    data: { /* I can't find a way */},
    dataType:"json",
    success: function (data) {
    var div = document.createElement('div');
    document.getElementById('names').appendChild(div);
    } 
});
})

Python:

@app.route("/")
def index():
     return render_template('index.html')

@app.route("/regist")
def register():
    cknames = request.form.getlist('check')
    return cknames %??

In addition I don’t want to redirect the page, want to just add div element. Appreciate any helps!

Source: Python Questions

LEAVE A COMMENT