Help! Problems filling a table dynamically with AJAX

1

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?

    
asked by RolandF 01.05.2018 в 00:09
source

2 answers

1

Your problem is that you re-write the table inside your for loop. The correct way would be like this:

        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);
    
answered by 01.05.2018 / 00:16
source
0

remove var show="";

Try changing this in this way with array_push ()

array_push($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,
                  )
);

Just use append to add the elements to your table, like this:

var 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").append(mostrar);//Aqui agregamos la tr a la tabla

as with

$("#llenarTabla").html(mostrar);

You just overwrite the data with each line, so I showed you only the last one

Example:

$(function(){
	$(".cargar").click(function(){
  	$.get('https://test-163a4.firebaseapp.com/lista.json?callback=?', function(data){
      $("#cuerpo").html("");
      for(var i=0; i<data.datos.length; i++){
      	var tr = '<tr>
        	<td>'+data.datos[i].nombre+'</td>
          <td>'+data.datos[i].apellido+'</td>
          <td>'+data.datos[i].cargo+'</td>
          <td>'+data.datos[i].empresa+'</td>
        </tr>';
        $("#cuerpo").append(tr)
      }
    })    
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>
  Prueba de tabla Cargada desde JSON
</h1>
<button class="cargar">
  Cargar Lista
</button>
<table>
  <thead>
    <th>Nombre</th>
    <th>Apellido</th>
    <th>Cargo</th>
    <th>Empresa</th>
  </thead>
  <tbody id="cuerpo">
    
  </tbody>
</table>
    
answered by 01.05.2018 в 01:13