send checkbox values as fix by ajax [duplicated]

0

hello I have the following problem .. I need to send the values of a group of checkbox in an array, through ajax and process them in php with codeigniter. I am starting with ajax so I do not know much about the matter, its contribution would be very important, I have the following code:

<form id="formid">
  <input type="checkbox" value="1" name="page[]" class="up">
  <input type="checkbox" value="2" name="page[]" class="up">
  <input type="checkbox" value="3" name="page[]" class="up">
  <input type="checkbox" value="4" name="page[]" class="up">
  <input type="checkbox" value="5" name="page[]" class="up">
  <a href="#" id="enviar" />Enviar</a>
</form>


<script type="text/javascript">
$(document).ready(function() {
    $('#enviar').click(function(){
        var selected = '';    
        $(":checkbox[name=page]").each(function(){
            if (this.checked) {
                selected += $(this).val()+', ';
            }
        }); 
        if (selected != '') 
            $.ajax({
            cache: false,
            type: 'post',
            data: selected,
            url: 'roles/paginas',
            success: function(data){
            alert('datos enviados');
            }
           }); 
        else
            alert('Debes seleccionar al menos una opción.');

        return false;
    });         
});    
</script>

How can I send the values in an array and process them in my controller in php

    
asked by FeRcHo 25.01.2017 в 22:44
source

1 answer

2

There is an error and other things to improve in this code:

  • The error: Where you put the checkboxes, use name="page" instead of name="page[]" otherwise you can not find what you are trying to find.

  • Improvements: You should use json to send data because it is a standard, it is readable, there are already robust ways to generate and parse it, etc. So I made some small changes that comment on the code so you can see them.

  • The main one is to use dataType: "json" in the ajax request since this causes it to be sent (and the response is received, if any) structured and direct in the form of objects without having to be parsing manually.

    The rest are commented on in the code, like using an Array instead of a string to arm the array.

    Salu2

    $(document).ready(function() {
      $('#enviar').click(function() {
        // defines un arreglo
        var selected = [];
        $(":checkbox[name=page]").each(function() {
          if (this.checked) {
            // agregas cada elemento.
            selected.push($(this).val());
          }
        });
        if (selected.length) {
    
          $.ajax({
            cache: false,
            type: 'post',
            dataType: 'json', // importante para que 
            data: selected, // jQuery convierta el array a JSON
            url: 'roles/paginas',
            success: function(data) {
              alert('datos enviados');
            }
          });
    
          // esto es solo para demostrar el json,
          // con fines didacticos
          alert(JSON.stringify(selected));
    
        } else
          alert('Debes seleccionar al menos una opción.');
    
        return false;
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form id="formid">
      <input type="checkbox" value="1" name="page" class="up">
      <input type="checkbox" value="2" name="page" class="up">
      <input type="checkbox" value="3" name="page" class="up">
      <input type="checkbox" value="4" name="page" class="up">
      <input type="checkbox" value="5" name="page" class="up">
      <a href="#" id="enviar" />Enviar</a>
    </form>

    Then, to get this fix in PHP you need to do something similar to the following:

    // obtienes el cuerpo del POST
    $entityBody = file_get_contents('php://input');
    
    // decodificas el JSON
    $data = json_decode($entityBody, true); // true es para recibir un array en $data
    
    print_r($data); // ["1","2","3","4","5"] si estan todos seleccionados. 
    
        
    answered by 25.01.2017 / 23:09
    source