Pass array obtained from fetch (PDO :: FETCH_ASSOC) to javascript

0

I'm trying to make a table and I'm having problems with the edit button. I want to click on this button to load the data that is in the table to the form from the BD. So for this I want to send the string I get from the database with fetch to a javascript function:

$statement = $conexion->prepare('SELECT idMascota, Nombre_mascota, Tipo_mascota, Raza_mascota, Color_mascot, Foto_mascota, Residente_idResidente FROM mascota WHERE  Residente_idResidente = :idResidente ');
            $statement->execute(array(':idResidente' => $idResidente)); 
            //print_r($statement->fetch(PDO::FETCH_ASSOC));/*regresa Array ( [idMascota] => 1 [Nombre_mascota] => Zeus [Tipo_mascota] => Perro [Raza_mascota] => French Poodle [Color_mascot] => Cafe [Foto_mascota] => (regresa la imagen en binario ���J...)

        /*  $row2 = $statement->fetch(PDO::FETCH_ASSOC);
            echo json_encode($row_json); regreso null*/ 


            while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {//FETCH_ASSOC  me regresa un array con todos los elementos
                $mascota = array('idMascota' => $row['idMascota'],
                                 'Nombre_mascota' => $row['Nombre_mascota'],
                                 'Tipo_mascota' => $row['Tipo_mascota'],
                                 'Raza_mascota' => $row['Raza_mascota'],
                                 'Color_mascot' => $row['Color_mascot'], 
                                 'Foto_mascota' => base64_encode($row['Nombre_mascota']),);

         ?>
        <tr>
            <td><?php echo $row['Nombre_mascota'] ?></td><!--llamo al elemento Nombre_mascota-->
            <td><?php echo $row['Tipo_mascota'] ?></td><!--llamo al elemento Tipo_mascota-->
            <td><?php echo $row['Raza_mascota'] ?></td><!--llamo al elemento Raza_mascota-->
            <td><?php echo $row['Color_mascot'] ?></td><!--llamo al elemento Color_mascot-->
            <td><img height="70px" src="data:image/jpg;base64,<?php echo base64_encode($row['Foto_mascota']); ?>"/></td>    

            <td>
                <button class="btn btn-warning glyphicon glyphicon-pencil" data-toggle="modal" data-target="#modalEdicion" onclick="agregaform('<?php echo json_encode($mascota); ?>')">

                </button>
            </td>

This is the javascript function:

function agregaform(datos){

    var data = datos;

    //d=datos.split('||');

    $('#idMascota').val(data['idMascota']);
    $('#nombreu').val(data['Nombre_mascota']);
    $('#tipou').val(data['Tipo_mascota']);
    $('#razau').val(data['Raza_mascota']);
    $('#coloru').val(data['Color_mascot']);
}

The idea of sending the fix from php to javascript is that I want to click on the edit button to show me the data that is currently on the form. This is the table:

Clicking on the button shows this form (which is where I want to put the elements of the arrangement so that it is filled with the info that is already in the table)

I think where I am failing is to add the data to the form with javascript because I already get the data as in the next photo but nothing comes out in the form

    
asked by Antonio Méndez 23.02.2018 в 03:50
source

3 answers

0

Finish by using the following function, where I specify the name of the form and the input. I had already resolved it but I forgot to comment, thanks to those who answered me.

function agregaform(datos){

d=datos.split('||');

    document.update.idMascota.value = d[0];
    document.update.nombreu.value = d[1];
    document.update.tipou.value = d[2];
    document.update.razau.value = d[3];
    document.update.coloru.value = d[4];
}
    
answered by 23.02.2018 / 06:04
source
1

Seeing the problem you have, when doing the printing of the table showing the pets, on the td that contains the button that you click to launch the popup, you place the id of the pet, so that it is

<td id="56"><button> Editar</button></td>

inside the javascript you make the impression of your data with, echo json_encode($arreglo_mascotas);

which should look like this

var mascotas = [{"id":"56", "nombre":"Katy", .....}];

In the click event of your edit button, you get the id of td who is the parent of your button

var id = $(this).parent().attr('id');
// hacer busqueda sobre tus mascotas
$.each(mascotas, function(key, mascota){
if(mascota.id == id){
    $('#idMascota').val(mascota['idMascota']);
    $('#nombreu').val(mascota['Nombre_mascota']);
    $('#tipou').val(mascota['Tipo_mascota']);
    $('#razau').val(mascota['Raza_mascota']);
    $('#coloru').val(mascota['Color_mascot']);
}

});

The example of ajax is very simple add this line in your html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

you can add it in the header head or within body only until the end, with this you include the code of jquery, and you add the following script to execute the call ajax

<script>
$(document).ready(function () {
    // Puedes colocarlo dentro de un evento, como dar click a un botón
    $.ajax({
        url:'http://pagina/para/obtener/datos.php',
        success:function(res){
            // aqui colocarias los datos sobre los campos que necesitas
            // caso en el que la respuesta sea solo un objeto
            $('#idMascota').val(res['idMascota']);
            $('#nombreu').val(res['Nombre_mascota']);
            $('#tipou').val(res['Tipo_mascota']);
            $('#razau').val(res['Raza_mascota']);
            $('#coloru').val(res['Color_mascot']);

            // esto es en caso que la respuesta sea un arreglo
            $.each(res, function(key, object){
                $('#idMascota').val(object['idMascota']);
                $('#nombreu').val(object['Nombre_mascota']);
                $('#tipou').val(object['Tipo_mascota']);
                $('#razau').val(object['Raza_mascota']);
                $('#coloru').val(object['Color_mascot']);
            });
        },
        error:function(err){
            alert("Ha ocurrido un error");
        }
    });
});
</script>
    
answered by 23.02.2018 в 05:18
0

What you should do is add the column number of each result of your database.

$statement = $conexion->prepare('SELECT idResidente, idMascota, Nombre_mascota, Tipo_mascota, Raza_mascota, Color_mascot, Foto_mascota, Residente_idResidente FROM mascota WHERE  Residente_idResidente = :idResidente ');
$statement->execute(array(':idResidente' => $idResidente));
$row2 = $statement->fetch(PDO::FETCH_ASSOC);
echo "window.JSON = ".json_encode($row2);
    while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
    ?>
<tr>
    <td><?php echo $row['Nombre_mascota'] ?></td>
    <td><?php echo $row['Tipo_mascota'] ?></td>
    <td><?php echo $row['Raza_mascota'] ?></td>
    <td><?php echo $row['Color_mascot'] ?></td>
    <td><img height="70px" src="<?php echo $row['Foto_mascota']); ?>"/></td>
    <td>
        <button class="btn btn-warning glyphicon glyphicon-pencil" data-toggle="modal" data-target="#modalEdicion" onclick="agregaform(window.JSON[<?php echo $row["idResidente"]; ?>])"> // $idResidente debe ser un numero (0, 1, 2, 3, ...) dependiendo el numero de la columna de tu base de datos y deberia imprimir algo asi window.JSON[0]

            </button>
        </td>

        <script>
            function agregaform(data){
                $('#idMascota').val(data['idMascota']);
                $('#nombreu').val(data['Nombre_mascota']);
                $('#tipou').val(data['Tipo_mascota']);
                $('#razau').val(data['Raza_mascota']);
                $('#coloru').val(data['Color_mascot']);
            }
        </script>

I hope to help you out

    
answered by 23.02.2018 в 05:35