Pass data from JS to PHP

0

How can I not pass certain data from js to php:

The structure of some radios buttons

<input class="rad" name="1" id="106" value="0" type="radio">
<input class="rad" name="1" id="45" value="0" type="radio">
<input class="rad" name="2" id="12" value="0" type="radio">
<input class="rad" name="2" id="23" value="0" type="radio">

The JavaScript code:

function guardar(){
  //Declaramos un objeto
 var obj = {};

 //iteramos todo lo que tenga clase rad
 $('.rad').each(function(){

  //Validamos si está chequeado
  if( $(this).is(':checked') ){

    //sacamos el heat en el que se encuentre
    var heat = $(this).attr('name');

    //creamos un nodo con el nombre del heat
     obj[ heat ] = {};

    //Agregamos la información al nodo con el nombre del heat
    obj[ heat ]['id'] = $(this).attr('id');
   // obj[ heat ]['value'] = $(this).val();
  }
 });

 console.log('Esto es lo que se enviará al PHP');
 console.log(obj);

 //abrimos la petición AJAX y no le parseamos ni nada, así pasamos el objeto al nodo "data"
  $.ajax({
    url: 'decode.php',
    method: 'GET',
    data: obj, 
    success:function(response){
      console.log(response);
    },
    error: function(e){
      console.log('Error! El error está en que esta parte no está conectada a tu Back-end');
    }
  })

In PHP :

<?php

var_dump( $_REQUEST );

$heat1_id = $_REQUEST['heat1']['id'];

echo $heat1_id;

?>

Performing a test returns the following:

Javascript

PHP

array(0) { } 

Many thanks to: @TO. Cedano for the orientation

and the last code you used was from @Alberto Siurob

    
asked by Jess182 14.05.2018 в 18:56
source

3 answers

1

The fundamental question is that you correctly recover the radio button and the established values.

A simple way to do it would be this:

JS / jQuery

$(
  function() {
    $("#frmPersonas").on("submit", function(e) {
      e.preventDefault();
      var jsonData = {objeto:"objeto"};
      $("#frmPersonas input[type=checkbox]").each(function() {
        jsonData[this.name] = this.checked;
      });
      
      console.log(jsonData);

/*PETICIÓN AJAX: descomenta este bloque

            $.ajax({
                data: jsonData,  //<--- ***Atención a esto***
                type: "GET",
                dataType: "json",
                url: "decode.php",
            })
             .done(function( data, textStatus, jqXHR ) {
                 if ( console && console.log ) {
                     console.log( "La solicitud se ha completado correctamente." );
                 }
             })
             .fail(function( jqXHR, textStatus, errorThrown ) {
                 if ( console && console.log ) {
                     console.log( "La solicitud a fallado: " +  textStatus);
                 }
            });


*/


    });
  }
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Formulario simple que enviará una petición POST -->
<form id="frmPersonas" action="" method="post">
  <label for="POST-name">Nombre  :</label>
  <input id="POST-name" type="text" name="name" value="Prueba" /><br /> Uno:
  <input type="checkbox" name="chkUno" id="chkUno" checked /> <br /> Dos:
  <input type="checkbox" name="chkDos" id="chkDos" /> <br /> Tres:
  <input type="checkbox" name="chkTres" id="chkTres" checked /> <br /> Cuatro:
  <input type="checkbox" name="chkCuatro" id="chkCuatro" /> <br />
  <hr />
  <input type="submit" value="Enviar">
</form>

Then, you send the jsonData object to the server using Ajax.

Note that here you have a correct json object, to which you can add some other key you want to identify it later in PHP.

This is an automatic code that gets the value of each radio button, when it is selected, the value will be true , while if it is not, the value will be false . You can take advantage of that possibility, which is also safer than setting yourself manual values set to 1 and 0 . You only have to take it into account where you are going to use the data, that is, instead of verifying if the value is equal to 1 or a 0 , you will verify if it is true or false .

I think everything else is a piece of cake, because the great difficulty of your code was here, now, it's just a matter of passing jsonData to the server and that's it.

PHP

On the server, you can treat the request like this:

$data= (isset($_GET["objeto"])) ? json_decode($_GET['objeto']) : array ("error"=>"No se posteó la clave objeto");
var_dump($data);

If you have any difficulty, tell me about it.

I hope it serves you.

    
answered by 14.05.2018 в 19:54
0

What you were doing was not bad, just that you had to set a header and the way to send the data was wrong.

pure javascript

function guardarmarcas(e) {
  var btnid = e.id;
  var arrbtnid = btnid.split("");
  var num = arrbtnid[3];
  var arrradios = document.getElementsByName(num);
  //console.log(arrradios);

  var arrradios2 = {};

  for (var i = 0; i < arrradios.length; i++) {

    arrradios2[arrradios[i].id] = arrradios[i].checked == true ? "1" : "0"
  }


  var jsonradios = JSON.stringify({objeto: arrradios2});
  console.log(jsonradios);

  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var response = xhr.responseText;
      console.log(response);
    }
  };
  // url del php
  xhr.open("GET", "decode.php", true);
  // seteo el header como json
  xhr.setRequestHeader("Content-Type", "application/json");
  // envío los datos
  xhr.send(jsonradios);
}

javascript with jQuery

$.ajax({
  data: {objeto: arrradios2},
  type: "GET",
  dataType: "json",
  url: "decode.php",
})
.done(function( data, textStatus, jqXHR ) {
  if ( console && console.log ) {
    console.log( "La solicitud se ha completado correctamente.");
  }
})
.fail(function( jqXHR, textStatus, errorThrown ) {
  if ( console && console.log ) {
    console.log( "La solicitud a fallado: " +  textStatus);
  }
});
    
answered by 14.05.2018 в 19:21
0

It's easy boy.

/*
1. Ponle una misma clase a todos los radios, por ejemplo rad. (Podemos hacer la selección con un selector complejo '$('input[type="radio"]')' pero no se si tengas más selectores de tipo radio en el DOM y esos no los necesitamos.*/
  
   function guardar(){
      //Declaramos un objeto
     var obj = {};
     
     //iteramos todo lo que tenga clase rad
     $('.rad').each(function(){
      
      //Validamos si está chequeado
      if( $(this).is(':checked') ){
      
        //sacamos el heat en el que se encuentre
        var heat = $(this).attr('name');
        
        //creamos un nodo con el nombre del heat
         obj[ heat ] = {};
         
        //Agregamos la información al nodo con el nombre del heat
        obj[ heat ]['id'] = $(this).attr('id');
        obj[ heat ]['value'] = $(this).val();
      }
     });
     
     console.log('Esto es lo que se enviará al PHP');
     console.log(obj);

     //abrimos la petición AJAX y no le parseamos ni nada, así pasamos el objeto al nodo "data"
      $.ajax({
        url: 'decode.php',
        method: 'GET',
        data: obj, 
        success:function(response){
          console.log(response);
        },
        error: function(e){
          console.log('Error! El error está en que esta parte no está conectada a tu Back-end');
        }
      })
   }
  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<br>Heat1<br><hr>
<input type="radio" class="rad" name="heat1" value="uno" id="1">
<input type="radio" class="rad" name="heat1" value="dos" id="2">

<br>Heat2<br><hr>
<input type="radio" class="rad" name="heat2" value="tres" id="3">
<input type="radio" class="rad" name="heat2" value="cuatro" id="4">

<br>Heat3<br><hr>
<input type="radio" class="rad" name="heat3" value="cinco" id="5">
<input type="radio" class="rad" name="heat3" value="seis" id="6">

<br>Heat4<br><hr>
<input type="radio" class="rad" name="heat4" value="siete" id="7">
<input type="radio" class="rad" name="heat4" value="ocho" id="8">

<br>Heat5<br><hr>
<input type="radio" class="rad" name="heat5" value="nueve" id="9">
<input type="radio" class="rad" name="heat5" value="diez" id="10">


<br><br><br><input type="button" value="Guardar" onclick="guardar()">

In PHP

 //Si quieres ver toda la información, $_REQUEST responde a los verbos GET y POST
var_dump( $_REQUEST );

//Para acceder a los nodos y al valor es fácil, por ejemplo
$heat1_val = $_REQUEST['heat1']['value'];
$heat1_id = $_REQUEST['heat1']['id'];
echo $heat1_val;
echo $heat1_id;
    
answered by 14.05.2018 в 20:06