2

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!

3
  • Just captures all the looping checkboxes with an array so you can easily process it. Commented May 5, 2021 at 2:16
  • Thanks to quick comment @MuthulakshmiM. I'm unfamiliar with flask and javascript. Could you teach me more details? Commented May 5, 2021 at 2:22
  • Push values inside array and don't forget to send csrf token as well . Commented May 5, 2021 at 13:01

1 Answer 1

1

You can use $('[name=check]').serialize() to get the data but your request is wrong.
Data received from form.getlist needs to be sent via POST and in form-data format.

$('a#add').bind('click',function(){    
    $.ajax({
        url: "/regist",
        type: "POST",
        data: $('[name=check]').serialize(),
        dataType:"json",
        success: function (data) {
            var div = document.createElement('div');
            document.getElementById('names').appendChild(div);
        },
        error: function(){
            console.log(arguments);
        }
    });    
})
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for great idea, @Musa. However, I still get stuck... I first rewrote to ck=request.get_json() and cknames=ck['check'] as you mention but any response don't appear. What are my mistakes??
Did request.form.getlist('check') not work?
OMG, I misunderstood your comment... request.form.getlist('check') works well and what I want is obtained. Thank you so much @Musa!!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.