Karlom Karlom - 21 days ago 5
Javascript Question

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.

Answer

You're missing the data property.

See: JQuery $.ajax() post - data for an example.

If you want to send the contents of the form, then you would use Form.serialize(), but you could put whatever data you want into the property.

$(document).ready(function() {
  $('.mychoice').click(function() {
    var formData = $('#myForm').serialize();
    console.log('Posting the following: ', formData);
    
    $.ajax({
      url: '/someurl',
      data: formData,
      type: 'post',
      dataType: 'json',
      success: function(data) {
        //  ... do something with the data...
      }
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/someurl" method="post" id="myForm">
  <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>