How to display json data in HTML

1

My problem is this, I need to print the data of a json in HTML, what I need to do is have a search input by ID or identification number, and that by pressing search I will show in a form the data that match with that number to be able to edit them, what I have tried is the following:

AJAX REQUEST

function viewPersona(){
 var result;
 jQuery(document).on('submit','#form_busqueda', function(event){
 event.preventDefault();

jQuery.ajax({
  url:'ajax.php?mode=view_persona',
  type: 'POST',
  dataType: 'json',
  data: $(this).serialize(),
})

   .done(function(resp){
      console.log(resp);
      if(resp.respuesta == '0'){
        result = '<div class="alert alert-danger alert-fill alert-close alert-dismissible fade in" role="alert">';
        result += '<center><h3>Llena el campo</h3></center></div>';
        $('#resultado').html(result);
      } else {
        if(resp.respuesta == 'vacio'){
          $("#loading").hide();
          result = '<div class="alert alert-danger alert-fill alert-close alert-dismissible fade in" role="alert">';
          result += '<center><h3>No existen registros con esta cedula</h3></center></div>';
          $('#resultado').html(result);
        } else {
          for(var i = 0; i< resp.respuesta.length; i++){
            var cod = resp.respuesta[i].inpersonas;
            var nombres = resp.respuesta[i].nombre;
            var ape = resp.respuesta[i].apellido;
            var cedula = resp.respuesta[i].cedula;
            var email = resp.respuesta[i].email;
            var date = resp.respuesta[i].fechanacimiento;
            var estado = resp.respuesta[i].tkd_estado;
            var perfil = resp.respuesta[i].perfiles;
          }
          result = '<input type="text" class="form-control" value="' + nombres + '" readonly></fieldset></div>';
          $("#AJAX_MOD_IN").html(result);
        }
      }
  })
 });
}

PHP

<?php
 if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && 
 strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
  if(!empty($_POST['busqueda'])){
   $db = new Conexion();
   sleep(1);
   $busqueda = $_POST['busqueda'];
   $sql = $db->prepare("SELECT * FROM tkd_personas INNER JOIN tkd_estados ON tkd_personas.id_estado = tkd_estados.id_estado WHERE tkd_personas.cedula = ? LIMIT 1");
    $sql->execute(array($busqueda));
     if($db->rows($sql)>0){
       $row = $db->recorrer($sql);
       echo json_encode(array('respuesta'=>$row));
     } else {
       echo json_encode(array('respuesta'=>'vacio'));
     }
   } else {
     echo json_encode(array('respuesta'=>'0'));
   }
  } else {
    header('location:?view=index');
  }
 ?>

AND THIS IS THE JSON THAT SHOWS ME console.log

The form is showing it, but when I print the data inside the input value, it says undefined.!

Thanks in advance to anyone who helps me!

    
asked by Alejo Mendoza 16.03.2018 в 08:28
source

2 answers

1

So it seems that in the last else you are not accessing the object "answer" (or the one that contains the data returned)

success
Type: Function( Anything data, String textStatus, jqXHR jqXHR )

    else {
              for(var i = 0; i< resp.respuesta.length; i++){
                var cod = resp.respuesta[i].inpersonas;
                var nombres = resp.respuesta[i].nombre;
                var ape = resp.respuesta[i].apellido;
                var cedula = resp.respuesta[i].cedula;
                var email = resp.respuesta[i].email;
                var date = resp.respuesta[i].fechanacimiento;
                var estado = resp.respuesta[i].tkd_estado;
                var perfil = resp.respuesta[i].perfiles;
              }
    
answered by 16.03.2018 в 10:48
0

The problem is that you do not reveal the structure of what you receive with ajax, so it is impossible to know exactly what is wrong. You should put the result of the console.log so that we can see what the server sends you. For my part I have made an interpretation of what may be happening to you.

For this, what I interpret is that answer is the "ok" that you receive the answer correctly, so you have to go through another array that you have with the answer variable, which I interpret that it is data.

I imagined that in the json you have an array of this style:

resp: {
 respuesta: '',
 datos: {
         {
          inpersonas: '',
          nombre: '',
          apellido:'',
          cedula:'',
          email:'',
          fechanacimiento:'',
          tkd_estado:'',
          perfiles:''
         },

        {
          inpersonas: '',
          nombre: '',
          apellido:'',
          cedula:'',
          email:'',
          fechanacimiento:'',
          tkd_estado:'',
          perfiles:''
         },
         //(repetido x veces...)
        }

}

So you should go through the array like this:

else {
      for(var i = 0; i< resp.datos.length; i++){
        var cod = resp.datos[i].inpersonas;
        var nombres = resp.datos[i].nombre;
        var ape = resp.datos[i].apellido;
        var cedula = resp.datos[i].cedula;
        var email = resp.datos[i].email;
        var date = resp.datos[i].fechanacimiento;
        var estado = resp.datos[i].tkd_estado;
        var perfil = resp.datos[i].perfiles;
      }
    
answered by 16.03.2018 в 11:33