vendredi 22 septembre 2017

Jquery form.serialize() do not manage checkboxes properly

I have a problem on an ajax form submission with Jquery.

Ajax call is working fine but my server receives only the last checked checkbox in the request data. This happens because formdata generated by the serialize function (and passed to my request headers) is formatted as follow

configuration[accessoires]:2
configuration[accessoires]:3

instead of

configuration[accessoires][0]:2
configuration[accessoires][1]:3

This is my code :

$(document).ready(function () {
  $('body').on('submit', 'form[name="configuration"]', function (e) {
    e.preventDefault();
    var $form = $('form[name="configuration"]');
    var formData = $form.serialize(); // same result with $(this).serialize() or serializeArray()
    $.ajax({
        url : $form.attr('action'),
        type: $form.attr('method'),
        data : formData,
        success: function(html) {
          // success code
        }
    });
  });
});
<script src="http://ift.tt/1oMJErh"></script>
<form name="configuration" action="blabla" method="POST">
  <input id="accessoire1" name="configuration[accessoires]" value="1" type="checkbox">
  <label for="accessoire1">blabla 1</label>
  
  <input id="accessoire2" name="configuration[accessoires]" value="2" type="checkbox">
  <label for="accessoire2">blabla 2</label>
  
  <input id="accessoire3" name="configuration[accessoires]" value="3" type="checkbox">
  <label for="accessoire3">blabla 3</label>
  
  <button id="app_submit">
    <span>submit</span>
  </button>
</form>

I am probably missing something but it looks like jquery doesn't detect my inputs are checkboxes with the same name.




Aucun commentaire:

Enregistrer un commentaire