mardi 22 septembre 2015

How to send unchecked checkbox with JSON And AJAX

It was clearly well explained Here and here. Sometime we want to save the unchecked state, and I can't do that with an Hidden field for this because i post data with JSON by this :

$(".switch-checkbox").on('switchChange.bootstrapSwitch', function(event, state) {
    event.preventDefault();
    var data = JSON.stringify($('form[name="option"]').serializeArray());
    $.ajax({
      url: "<?php echo $this->url('widget/saveConfigure') ?>",
      dataType: 'json',
      contentType: 'application/json',
      async: true,
      data: data,
      type: 'post',
      beforeSend : function() {
        $(".flash-message > p").html('');
        $('.flash-message').addClass("hidden");
      },
      success: function (data) {
        $(".flash-message > p").html('').append("Changement pris en compte avec succès");
        $('.flash-message').removeClass("hidden");
      },

      error: function () {
          console.log("Error...");
      }
    });
  });

My form has many checkbox, I have to generate a Json like this when a checkbox is checked :

[{"name":"idConfig","value":"12"},{"name":"addDataFac","value":"1"}]

and when it's not checked

[{"name":"idConfig","value":"12"},{"name":"addDataFac","value":"0"}]

But the tricky part, is, that form is completely dynamic and generated by a ZF2 script. I don't know the names of the checkbox.




Aucun commentaire:

Enregistrer un commentaire