I try to fill a table in html
from a query ajax
and php
.
Problem: I want to get the dependencies of a MySQL
table (I only have one added). But in php I input an array to return it to me in the ajax.
clases.php
<?php
if ($num_rows>=1) {
//Se obtienen los resultados de la consulta
while ($this->consulta->fetch()) {
if($id_Estado == 1){
//Se guardan los datos en un arreglo
$datos_json = array("Id_Dependencia"=>$id_dependencia ,"Nombre_Dependencia"=>$nombre_dependencia, "Id_Estado"=> $id_Estado, "Estado"=>"Activo");
}else{
$datos_json = array("Id_Dependencia"=>$id_dependencia,"Nombre_Dependencia"=>$nombre_dependencia, "Id_Estado"=> $id_Estado, "Estado"=>"Inactivo");
}
}
header('Content-type: application/json; charset=utf-8');
//Se devuelve el array pasado a JSON como objeto
echo json_encode($datos_json, JSON_FORCE_OBJECT);
}
?>
At the time of receiving the data in ajax
is done correctly, but when I want to fill some field of my table I have the following problem:
As an additional note I am using the function
.each
ofJQuery
.
ajax.js
function todasLasDependencias(){
$.ajax({
url: '../../php/instancias.php',
type: 'POST',
data: {Funcion: 'Dependencias-todas'},
})
.done(function(data) {
var tbHtml='';
//Esta funcion recorre el array JSON devuelto por la consulta
$.each(data.Nombre_Dependencia, function(index, val) {
//Se asigna en una variable lo que sera nuestra tabla
tbHtml +="<tr><th scope='row'>"+data.Nombre_Dependencia[index]+"</th></tr>";
});
$('#bodyTable-ND').append(tbHtml);
})
.fail(function() {
console.log("error");
});
}
Problem Case # 2: If I make some modifications in the script
where I have the ajax:
Modified code ajax.js
function todasLasDependencias(){
$.ajax({
url: '../../php/instancias.php',
type: 'POST',
data: {Funcion: 'Dependencias-todas'},
})
.done(function(data) {
var tbHtml='';
//Esta funcion recorre el array JSON devuelto por la consulta
$.each(data, function(index, val) {
//Se asigna en una variable lo que sera nuestra tabla
tbHtml +="<tr><th scope='row'>"+data.Nombre_Dependencia[index]+"</th></tr>";
});
$('#bodyTable-ND').append(tbHtml);
})
.fail(function() {
console.log("error");
});
}
I modified the parameters of the
.each()
function by adding onlydata
.
I just want to get the data without being quadrupled.
The structure of objeto json
is as follows: