I have tried to fill a table with data that is in a database, all through ajax. The query with the database is fine, like the sending of that data from a php file to a js file through ajax, the problem is filling the table with that data, only one row is shown, and true is that 2 rows should be shown, because that is the number of records that I have in my Mysql table.
Here I show you the code so you can see it better:
Here the consultation:
public function ListarEmpresas () {
global $conexion;
$listar = "SELECT * FROM empresa";
$query = $conexion->query($listar);
return $query;
}
Data received from the database:
$i = 1;
$data = Array();
$query_list = $objEmpresa->ListarEmpresas();
if (!empty($query_list)) {
while ($resp = $query_list->fetch_object()) {
$data[] = array("id"=>$i,
"Codigo"=>$resp->codigo,
"Empresa"=>$resp->NombreEmpresa,
"DocumentoTipo"=>$resp->tipo_documento,
"NumDoc"=>$resp->num_documento,
"Direccion"=>$resp->direccion,
"Telefono"=>$resp->telefono,
"Correo"=>$resp->email,
"Responsable"=>$resp->representante,
"Estado"=>$resp->estado,
);
$i++;
}
echo json_encode($data);
} else {
echo "error";
}
Here I receive the data:
$(document).ready(function() {
mostrar_Lista_Empresas ();
});
function mostrar_Lista_Empresas () {
var op = 'listar';
_ajax("../Controllers/EmpresaController.php", {op:op})
.done( function (info) {
//$("#llenarTabla").html(info);
//console.log(info);
var count2 = $(info).size();
//var count = Object.keys(info).length;
var mostrar = "";
var suscripcion = "";
var clase = "";
for (var i = 0; i < count2; i++) {
if (info[i].Estado == "A") {
suscripcion = "Gratuita";
clase = "gratis";
} else if(info[i].Estado == "P") {
suscripcion = "Paga";
clase = "paga";
}
mostrar = "<tr><td scope='row'>"+ info[i].id +"</td><td>"+
info[i].Codigo +"</td><td>"+ info[i].Empresa +"</td><td>"+
info[i].DocumentoTipo + ": " + info[i].NumDoc + "</td><td>"+
info[i].Telefono
+"</td><td>"+ info[i].Correo +"</td><td><span class='"+ clase
+"'>"+ suscripcion +"</span></td></tr>";
$("#llenarTabla").html(mostrar);
}
});
}
function _ajax(url, data) {
var ajax = $.ajax({
"method" : "POST",
"url" : url,
"data" : data,
"dataType" : "json"
})
return ajax;
}
The HTML where I show the data:
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>Codigo</th>
<th>Nombre Empresa</th>
<th>Documento</th>
<th>Telefono</th>
<th>Correo</th>
<th>Suscripción</th>
</tr>
</thead>
<tbody id="llenarTabla">
</tbody>
</table>
Here I show the image of the console where I show the result of "info", and I also show in console the value of count2. you can see that effectively the data is being received and that when using $ (info) .size (); I throw the size of "info", that is 2.
I have tried both with count and count2, the result is the same, only one row is shown, the last row. Here you can see:
It's really hard for me to see where the problem is, I do not know what I'm missing. Any suggestions?