Send checkbox with ajax jquery php

Asked

Viewed 4,340 times

6

I have the form to send/work perfectly with the other fields, but I cannot receive the checkbox selections. I need help to receive/manipulate in php:

THE 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 reception and creation of the variable or array (I don’t understand), in php. Help me?

  • 1 - no menhum id called "servicos" in your html. 2 - identifying multiple tags with id does not work. id is unique, use class. 3 - After taking the values correctly why not go through the ajax data correctly? you take the values with var services1 and play on date as services?! 4 - why not use serialize?

  • Gabriel, I’m a designer starting with web programming. I need help with this part.

2 answers

5


Vc can get checkbox values to send by 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 take the values. Just do it this way and assign the value in the service variable by the array above.

That is, [] at the end of the name is not necessary. If you want to pass only the checked values, you can also pass all the values. For that just remove the :checked of the selection.

Example: https://jsfiddle.net/9os3e18u/

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'>");
            (...)

Notice especially where I put comments between ***. Were the points where the code was changed.

And your HTML also has an error. It is not to put a different name in each one (servico1, servico2, etc). Name is the same in all. If you want to identify in a unique way use the id. It’s supposed to be like this:

<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>

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

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

Better understood now ? I recommend that instead of you using the value of each service as a string (e.g., "Sticking Film"), you replace it with a numerical value. It becomes easier to associate later in your bank.

You can ask more if you want.

0

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

So let’s go step by step.

1 Step - Pick up all the 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, for example services it is interesting to use an array, so I will show you the two forms:

As Array:

Riot your checkbox name to:

<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 this $_POST['servico'].

In its form with the name servico1, servico2 and servico3. You’d have to access each variable like this: $_POST['servico1'],$_POST['servico2'] etc....

  • And in php like $_POST['servicos'] or like $_POST['servico'] ?

  • Gabriel, the js got much leaner, but it doesn’t advance when I try to send.

Browser other questions tagged

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