'How to submit checkbox through jquery ajax?

I have difficulty submitting this form:

<form action="/someurl" method="post">
    <input type="hidden" name="token" value="7mLw36HxPTlt4gapxLUKWOpe1GsqA0I5"> 
    <input type="checkbox" class="mychoice" name="name" value="apple"> Apple
    <input type="checkbox" class="mychoice" name="name" value="orange"> Orange      
    <input type="checkbox" class="mychoice" name="name" value="pear"> Pear
  </form>

And the jquery bit:

$('.mychoice').click( function() {
    $.ajax({
        url: '/someurl',
        type: 'post',
        dataType: 'json',
        success: function(data) {
                 //  ... do something with the data...
                 }
    });
});

But nothing happens when I click a checkbox. How can I fix this?

UPDATE: It may worth mentioning that the form is located at a bootstrap modal.



Solution 1:[1]

Try this:

$(document).ready(function(){
    $('.mychoice').change( function() {
        $.ajax({
            url: '/someurl',
            type: 'post',
            dataType: 'json',
            success: function(data) {
                //  ... do something with the data...
            }
        });
    });
});

Solution 2:[2]

supply missing data

$(document).ready(function() {
  $('.mychoice').click(function() {
    $.ajax({
      url: '/someurl',
      data: $(this).closest('form').serialize(),
      type: 'post',
      dataType: 'json',
      success: function(data) {
        //  ... do something with the data...
      }
    });
  });
});

Solution 3:[3]

if you are trying to receive the data with the csrf token do as below :

var fd = new FormData()
fd.append('csrfmiddlewaretoken', document.getElementsByName('csrfmiddlewaretoken')[0].value)
fd.append('field_name', $("input[name='field_name']").serialize())

will return

['field_name=9&field_name=15&field_name=10']

you will then have to parse the info in your view ( django )

Solution 4:[4]

Try 'change' instead of 'click', like this:

$('.mychoice').change(function(){...})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 James McDowell
Solution 2
Solution 3 Drayen Dörff
Solution 4 evilReiko