Send checkbox with ajax jquery php

6

I have the form to send / work perfect with the other fields, but I can not receive the checkbox selections. I need help getting / manipulating in php:

HTML:

<div class="input-group">
    <label for="servicos">NECESSITA EMBALAGENS?</label>

    <div class="checkbox">
        <label><input type="checkbox" value="1" name="servicos">Pelicula Aderente</label>
    </div>

    <div class="checkbox">
        <label><input type="checkbox" value="2" name="servicos">Cartão Canelado</label>
    </div>

    <div class="checkbox">
        <label><input type="checkbox" value="3" name="servicos">Caixa Cartão</label>
    </div>

    <div class="checkbox">
        <label><input type="checkbox" value="4" name="servicos">Plástico Bolha</label>
    </div>
</div>

O .JS:

$(function() {
  $("input,textarea").jqBootstrapValidation({
    preventSubmit: true,
    submitError: function($form, event, errors) {
      // additional error messages or events
    },
    submitSuccess: function($form, event) {
      event.preventDefault(); // prevent default submit behaviour
      // get values from FORM
      var nome = $("#nome").val();
      var email = $("#email").val();
      var telefone = $("#telefone").val();

      var origem = $("#origem").val();
      var destino = $("#destino").val();
      var data_prevista = $("#data_prevista").val();
      var plano = $("#plano").val();

      var arr = [];
      $("input:checkbox[name=servicos]:checked").each(function() {
        arr.push($(this).val());
      });

      var como = $("#como").val();

      var descricao = $("#descricao").val();

      var Nome = nome; // For Success/Failure Message
      // Check for white space in name for Success/Fail message
      if (Nome.indexOf(' ') >= 0) {
        Nome = nome.split(' ').slice(0, -1).join(' ');
      }
      $.ajax({
        url: "././mail/contact_me.php",
        type: "POST",
        dataType: 'json',
        data: {

          nome: nome,
          email: email,
          telefone: telefone,
          origem: origem,
          destino: destino,
          data_prevista: data_prevista,
          plano: plano,
          servicos: arr,
          como: como,
          descricao: descricao
        },
        cache: false,
        success: function(data) {
          if (data.error) {
            // Fail message
            $('#success').html("<div class='alert alert-danger'>");
            $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;").append("</button>");
            $('#success > .alert-danger').append("<strong>Prezado(a) " + Nome + ", algo não está certo. Por favor, tente novamente.");
            $('#success > .alert-danger').append('</div>');
            //clear all fields
            $('#orcamento').trigger("reset");
          } else if (data.success) {
            // Success message
            $('#success').html("<div class='alert alert-success'>");
            $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;").append("</button>");
            $('#success > .alert-success').append("<strong>Prezado(a) " + Nome + ", sua mensagem foi enviada. Nós entraremos em contato consigo!</strong>");
            $('#success > .alert-success').append('</div>');
            //clear all fields
            $('#orcamento').trigger("reset");
          }
        }
      })
    },
    filter: function() {
      return $(this).is(":visible");
    },
  });
});


/*When clicking on Full hide fail/success boxes */
$('#nome').focus(function() {
  $('#success').html('');
});

PHP:

$nome = test_input($_POST['nome']);
$email = test_input($_POST['email']);
$telefone = test_input($_POST['telefone']);
$origem = test_input($_POST['origem']);
$destino = test_input($_POST['destino']);
$data_prevista = test_input($_POST['data_prevista']);
$plano = test_input($_POST['plano']);
$servicos = test_input($_POST['servicos']);
$como = test_input($_POST['como']);
$descricao = test_input($_POST['descricao']);

I think the code is all right, both html and js. The problem is the receipt and creation of the variable or array (I do not understand) in php. Help me?

    
asked by anonymous 10.05.2016 / 21:33

2 answers

5

You can get checkbox values to send per ajax like this:

html:

<div class="input-group">
  <label for="servicos">NECESSITA EMBALAGENS?</label>

  <div class="checkbox">
   <label><input type="checkbox" name="servicos" value="Pelicula Aderente">Pelicula Aderente</label>
  </div>

  <div class="checkbox">
   <label><input type="checkbox" name="servicos" value="Cartão Canelado" checked="checked">Cartão Canelado</label>
  </div>

  <div class="checkbox">
   <label><input type="checkbox" name="servicos" value="Caixa Cartão">Caixa Cartão</label>
  </div>

  <div class="checkbox">
   <label><input type="checkbox" name="servicos" value="Plástico Bolha" checked="checked">Plástico Bolha</label>
  </div>
</div>

js:

var arr = [];

$("input:checkbox[name=servicos]:checked").each(function(){
    arr.push($(this).val());
});

arr.forEach(function(item) {
    console.log(item ? 'true' : 'false');
});

This is an example of how to get the values. Just do it this way and assign the value in the servic variable by the above array.

That is, [] at the end of the name is not necessary. If you want instead of passing only the values checked, you can also pass all the values. To do this, just remove :checked from the selection.

Example: link

Edited to reply to comment

This is the right way:

        (...)
        var destino = $("#destino").val();
        var data_prevista = $("#data_prevista").val();       
        var plano = $("#plano").val();

        // *** aqui vc obtem o array com os valores ***
        var arr = [];            
        $("input:checkbox[name=servicos]:checked").each(function(){
            arr.push($(this).val());
        });

        var como = $("value#como").val();

        var descricao = $("#descricao").val();

        var Nome = nome; // For Success/Failure Message
        // Check for white space in name for Success/Fail message
        if (Nome.indexOf(' ') >= 0) {
            Nome = nome.split(' ').slice(0, -1).join(' ');
        }
        $.ajax({
            url: "././mail/contact_me.php",
            type: "POST",
            dataType: 'json',
            data: {

                nome: nome,
                email: email,
                telefone: telefone,

                origem: origem,
                destino: destino,
                data_prevista: data_prevista,                 
                plano: plano,
                // *** aqui está atribuindo os valores obtidos aos dados passados ao servidor ***
                servicos: arr,

                como: como,

                descricao: descricao                   

            },
            cache: false,
            success: function(data) {
                if(data.error){
                    // Fail message
                    $('#success').html("<div class='alert alert-danger'>");
            (...)

Note especially where I put comments between ***. It was the points where the code was changed.

And your HTML also has an error. It is not to put a different name on each one (service1, service2, etc). Name stays the same in all. If you want to uniquely identify, use the id. It's supposed to be this way:

<div class="input-group">
    <label for="servicos">NECESSITA EMBALAGENS?</label>

    <div class="checkbox">
        <label><input type="checkbox" value="Pelicula Aderente" name="servicos">Pelicula Aderente</label>
    </div>

    <div class="checkbox">
        <label><input type="checkbox" value="Cartão Canelado" name="servicos">Cartão Canelado</label>
    </div>

    <div class="checkbox">
        <label><input type="checkbox" value="Caixa Cartão" name="servicos">Caixa Cartão</label>
    </div>

    <div class="checkbox">
        <label><input type="checkbox" value="Plástico Bolha" name="servicos">Plástico Bolha</label>
    </div>
</div>

Dividing the jQuery tag that gets the values for you to understand better:

$("input:checkbox[name=servicos]:checked").each(function(){
    arr.push($(this).val());
});
  • input - > get all inputs
  • : checkbox - > of the checkbox type
  • [name = services] - > whose name is 'services'
  • : checked - > and are checked
  • .each (function () {-> and for each of them
  • arr.push ($ (this) .val ()); - > enter the value in array 'arr'

Better understood now? I recommend that instead of you use the value of each service as a string (eg: "Adherent Word"), you replace it with a numeric value. It is easier to associate later with your bank.

You can ask more if you want.

    
11.05.2016 / 00:36
0

As far as I understand, in the submitSuccess method is the place where you will collect form information and send it to php.

Let's go step by step.

1 Step - Get all fields.

var data = $("form").serialize();

2 Step - Send to php.

$.ajax({
  type: 'POST',
  url: 'arquivo.php',
  data: data,
  dataType: 'json',
  success: function() {

  },
  error: function(data) {

  }
});

3 Step - Read the fields in php

When you use grouped fields, such as services, it is interesting to use an array, so I'll show you both ways:

As Array:

Please type the name of your checkbox for:

<div class="checkbox">
  <label>
    <input type="checkbox" value="Pelicula Aderente" name="servico[]">Pelicula Aderente</label>
</div>

<div class="checkbox">
  <label>
    <input type="checkbox" value="Cartão Canelado" name="servico[]">Cartão Canelado</label>
</div>

And in php you can read so $_POST['servico'] .

In form with name service1, service2 and service3. You would have to access each variable like this: $_POST['servico1'] , $_POST['servico2'] etc ...

    
11.05.2016 / 15:12