Ajax with html checkbox

Asked

Viewed 245 times

1

I’m having trouble getting the value of the checkbox selected, php is taking the value of all checkbox including those that were not selected.

How would Ajax pass PHP only to those selected?

HTML Form:

<form method="post" action="javascript:;" id="form_cadastro" enctype="multipart/form-data">

<div class="form-check">
    <input type="checkbox" class="form-check-input" id="nenhum_tipo" value="nenhum_tipo">
    <label class="form-check-label" for="nenhum_tipo">Nenhum</label><br>

    <input type="checkbox" class="form-check-input" id="Bloco_1" value="Bloco_1">
    <label class="form-check-label" for="Bloco_1">Bloco 1 </label><br>

    <input type="checkbox" class="form-check-input" id="Bloco_2" value="Bloco_2">
    <label class="form-check-label" for="Bloco_2">Bloco 2 </label><br>

    <input type="checkbox" class="form-check-input" id="Bloco_3" value="Bloco_3">
    <label class="form-check-label" for="Bloco_3">Bloco 3 </label><br>

    <input type="checkbox" class="form-check-input" id="Bloco_4" value="Bloco_4">
    <label class="form-check-label" for="Bloco_4">Bloco 4 </label><br>

    <input type="checkbox" class="form-check-input" id="Bloco_5" value="Bloco_5">
    <label class="form-check-label" for="Bloco_5">Bloco 5 </label>
  </div>

</form>

Ajax JS

$(document).ready(function () {

    $('#form_cadastro').validate({ // initialize the plugin
        rules: {
            Nome: {
                required: true,
            },
            SobreNome: {
                required: true,
            }
        },


            messages: {
        required: "Campo obrigatório",
        remote: "Please fix this field.",
        email: "Por favor insira um email válido",
        url: "Please enter a valid URL.",
        date: "Please enter a valid date.",
        dateISO: "Please enter a valid date (ISO).",
        number: "Por favor digite apenas números.",
        digits: "Please enter only digits.",
        equalTo: "Please enter the same value again.",
        maxlength: $.validator.format( "Não insira mais do que {0} caracteres." ),
        minlength: $.validator.format( "Digite pelo menos {0} caracteres." ),
        rangelength: $.validator.format( "Please enter a value between {0} and {1} characters long." ),
        range: $.validator.format( "Please enter a value between {0} and {1}." ),
        max: $.validator.format( "Please enter a value less than or equal to {0}." ),
        min: $.validator.format( "Please enter a value greater than or equal to {0}." ),
        step: $.validator.format( "Please enter a multiple of {0}." )
    },
        submitHandler: function (form) { // for demo
 $(".resultado_form_cadastro").html('<div class="spinner"></div>');
var form = $('#form_cadastro');

var form_data = new FormData();

var nenhum_tipo = $("#nenhum_tipo").val();
var Bloco_1 = $("#Bloco_1").val();
var Bloco_2 = $("#Bloco_2").val();
var Bloco_3 = $("#Bloco_3").val();
var Bloco_4 = $("#Bloco_4").val();
var Bloco_5 = $("#Bloco_5").val();

form_data.append('nenhum_tipo', nenhum_tipo);
form_data.append('Bloco_1', Bloco_1);
form_data.append('Bloco_2', Bloco_2);
form_data.append('Bloco_3', Bloco_3);
form_data.append('Bloco_4', Bloco_4);
form_data.append('Bloco_5', Bloco_5);
$.ajax({
        url: 'http://xxxx/buscauiva/public_html/admin/form_cadastro.php', // point to server-side PHP script

        //url: 'http://buscaiuva.com.br/admin/validaAcesso.php', // point to server-side PHP script
        dataType: 'text',  // what to expect back from the PHP script, if anything
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,
        type: 'POST',

        success: function(php_script_response){
            //alert(php_script_response); // display response from the PHP script, if any
// pegando os dados

        }

     }).done(function(data){
                $('.resultado_form_cadastro').fadeOut('slow', function(){
                    $('.resultado_form_cadastro').fadeIn('slow').html(data);


                });
            })
            .fail(function(){
                alert('Ajax Submit Failed ...');
            });
            return false; // for demo
        }
    });
});

PHP

    $link = mysqli_connect("localhost","root","","database");

    mysqli_query($link,"INSERT INTO tipo_banner (id_empresa, nenhum, bloco1, bloco2, bloco3, bloco4, bloco5)
    VALUES ('".$id_empresas."', '".$_POST['nenhum_tipo']."', 

'".$_POST['Bloco_1']."', '".$_POST['Bloco_2']."', '".$_POST['Bloco_3']."', '".$_POST['Bloco_4']."', '".$_POST['Bloco_5']."')") 
or die(mysqli_error($link));

1 answer

1


You can do it like this:

<input type="checkbox" name="Bloco[]" value="1" />
<input type="checkbox" name="Bloco[]" value="2" />
<input type="checkbox" name="Bloco[]" value="3" />
 var blocos = new Array();
$("input[name='Bloco[]']:checked").each(function ()
{
  blocos.push( $(this).val());
});
  • returned an error Uncaught Referenceerror: Block is not defined at Htmlinputelement.<Anonymous> (company_register.php:506) at Function.each (jquery-3.3.1.min. js:2) at w.fn.init.each (jquery-3.3.1.min. js:2) at t.validator.submitHandler (empresas_cadastrar.php:504) at s (jquery.validate.js:1) at Htmlformelement.<Anonymous> (jquery.validate.js:1) at Htmlformelement.Dispatch (jquery-3.3.1.min. js:2) at Htmlformelement.y.Handle (jquery-3.3.1.min. js:2)

  • how to get this into my code?

  • error still persisted, you can show this in my code?

  • is returning this error now Uncaught Syntaxerror: Unexpected Identifier

  • little dot there rsrs, again var Bloco_1 = '; if($("#Bloco_1").is(':checked')) { Bloco_1 = $("#Bloco_1"). val(); }

  • is still picking up those who are not selected

  • 1

    Now just you do the same for the other blocks, you know? This example I gave was for block 1.

  • worked out buddy, thanks

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.