Add rows to the TBody of an HTML table with JavaScript

0

The problem I want to solve is to be able to add rows to a table with JavaScript, after having selected an Input Radio, the table should change.

The JavaScript code:

<script type="text/javascript">
$(document).ready(function() {
var valor = '';
$("input[name='rama']" ).on('change', function() {
Id = $(this).val();
alert(Id);
    $.post("../Sql/ArregloPersonas.php", {Id: Id
        }, function(data){
            $("#personas-rama").html(data);
    });
});
});
</script>

I understand that I can not do the post, I should pass the variable by the GET method, because like this, I do not recognize the variable, since the file that receives the variable is in JSON.

The code of the JSON file is:

<?php
header('Content-Type: application/json');
$conexion = new PDO("mysql:host=localhost;dbname=scouts_601_palmira","root","");

$idrama = $_POST['Id'];

$sql4 = "SELECT Primer_nombre, Numero_documento, Fecha_nacimiento, Id_cargo FROM Personas";
$sentencia4 = $conexion -> prepare($sql4);
$sentencia4 -> execute();
$personas = $sentencia4 -> fetchAll();

$sql5 = "SELECT Id FROM Cargos WHERE Id_rama =".$idrama."";
$sentencia5 = $conexion -> prepare($sql5);
$sentencia5 -> execute();
$cargos = $sentencia5 -> fetchAll();

for ($i=0; $i < count($personas); $i++) {
for ($j=0; $j < count($cargos); $j++) { 
    if ($personas[$i]['Id_cargo'] == $cargos[$j]['Id']) {
    $integrantes = array();
        array_push($integrantes, $personas[$i]);
    }
  }
}

echo json_encode($integrantes);
?>

This is where I do not get the variable from JavaScript, since I have to pass it through GET, but I do not know how it would look like.

Finally there is the code of the table:

<table>
<caption>Integrantes</caption>
<thead>
<tr>
    <th>Numero<br>documento</th>
    <th>Primer<br>nombre</th>
    <th>Segundo<br>Nombre</th>
    <th>Primer<br>apellido</th>
    <th>Segundo<br>apellido</th>
    <th>Inscripción</th>
    <th>Acción</th>
</tr>
</thead>
<tbody id="personas-rama" name="personas-rama">
</tbody>
</table>

I thank you in advance for any contribution to solve this problem.

    
asked by Danyel Melendez Ramirez 19.10.2018 в 17:54
source

1 answer

1

The following code could be applied in jquery once you get the data in json

var tr_html="";
$.each(data, function(i,val) {
   tr_html=tr_html+"<tr><td>"+val.Numero_documento+"</td><td>"+val.Primer_nombre+"</td><td></td><td></td></tr>";
});
$("#personas-rama").append(tr_html);//si se requiere remplazar el contenido debera ser html()
    
answered by 19.10.2018 / 20:56
source