MOSTRAR DATOS TABLA FETCH - JQUERY - XMLHTTPREQUEST - AXION - VUEJS CON PHP MYSQL API JSON

///////// API JSON/////////////////

<?php

header('Access-Control-Allow-Origin: *');

header('Access-Control-Allow-Headers: origin, x-requested-with, content-type');

header('Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTION');

header('Content-Type: application/json');

$conexion = new PDO("mysql:host=localhost;dbname=bdpersonas", "root", "root");

$dato_recibido = json_decode(file_get_contents("php://input"));

$datos = array();


//$consulta = "SELECT * FROM personas2 WHERE nombre LIKE '%{$dato_recibido->nombre}%' ORDER BY id DESC";

$consulta = "SELECT * FROM personas2 ORDER BY id DESC";

 $estado = $conexion->prepare($consulta);

 $estado->execute();


 while($registros = $estado->fetch(PDO::FETCH_ASSOC))

 {

  $datos[] = $registros;

 }


 echo json_encode($datos);


?>

/////////////////////////////////

 <button id="btn1">ver tabla</button>

<table>

        <thead>

            <tr>

                <th>Nombre</th>

                <th>Dni</th>

            </tr>

        </thead>

        <tbody id="resultados">

        </tbody>

    </table>



<script>


const boton1 = document.querySelector('#btn1');


boton1.addEventListener('click', () => {

  //  const nombre = buscarInput.value;

    fetch('api_cargar_tabla.php', {

        method: 'GET'

    })


    .then(response => response.json())


    .then(data => {


        const resultadosTabla = document.querySelector('#resultados');

        

        resultadosTabla.innerHTML = '';

       

        data.forEach(resultado => {


            const tr = document.createElement('tr');


            tr.innerHTML = `

                <td>${resultado.nombre}</td>

                <td>${resultado.dni}</td>

            `;


            resultadosTabla.appendChild(tr);


        });


    })

    .catch(error => console.log(error));

});



</script>

////////////////////////////////////////////////

<table>

    <thead>

        <tr>

            <th>Nombre</th>

            <th>Dni</th>

        </tr>

    </thead>

    <tbody id="resultados">

    </tbody>

</table>


<script>

    $.ajax({

        url: 'buscar.php',

        method: 'GET',

        dataType: 'json'

    }).done(function(resultados) {

        $('#resultados').empty();


        $.each(resultados, function(index, resultado) {

            var fila = $('<tr>').append(

                $('<td>').text(resultado.nombre),

                $('<td>').text(resultado.dni)

            );


            $('#resultados').append(fila);

        });

    }).fail(function() {

        alert('Hubo un error al cargar los datos.');

    });

</script>

Este código HTML y JavaScript realiza una solicitud AJAX a un archivo "buscar.php" utilizando el método GET y espera recibir una respuesta en formato JSON. Luego, recorre los resultados obtenidos y los muestra en una tabla HTML con dos columnas: "Nombre" y "Dni".


Agregué el cierre de la función .each y el uso de .append para agregar las filas a la tabla en el elemento con el id "resultados". También se agregó una función .fail para manejar errores en caso de que la solicitud AJAX falle.


Recuerda que necesitas incluir la biblioteca de jQuery en tu página para que este código funcione correctamente, ya que utiliza funciones de jQuery.





User

HACERLO CON LA LIBRERIA AXIOS LO ANTERIOR

ChatGPT

Para realizar la misma operación utilizando la librería Axios en lugar de jQuery, primero debes asegurarte de incluir la librería Axios en tu proyecto (generalmente, a través de un CDN o mediante la instalación de npm). Luego, puedes modificar el código para usar Axios en lugar de jQuery para hacer la solicitud AJAX. Aquí tienes el código adaptado:


html

Copy code

<!DOCTYPE html>

<html lang="es">

<head>

    <meta charset="UTF-8">

    <title>Tabla de resultados</title>

</head>

<body>


<table>

    <thead>

        <tr>

            <th>Nombre</th>

            <th>Dni</th>

        </tr>

    </thead>

    <tbody id="resultados">

    </tbody>

</table>


<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

<script>

    axios.get('buscar.php')

        .then(function (response) {

            // Se eliminan los resultados previos

            document.getElementById('resultados').innerHTML = '';


            // Se recorren los resultados obtenidos

            response.data.forEach(function (resultado) {

                // Se crea una fila y se agrega a la tabla

                var fila = document.createElement('tr');

                fila.innerHTML = '<td>' + resultado.nombre + '</td><td>' + resultado.dni + '</td>';

                document.getElementById('resultados').appendChild(fila);

            });

        })

        .catch(function (error) {

            alert('Hubo un error al cargar los datos.');

        });

</script>


</body>

</html>

Este código utiliza Axios para realizar la solicitud GET a "buscar.php" y luego procesa los resultados obtenidos para mostrarlos en la tabla HTML. La función .then maneja la respuesta exitosa de la solicitud, mientras que .catch maneja los errores en caso de que la solicitud falle.





User

HACERLO CON LA LIBRERIA AXIOS Y VUEJS

ChatGPT

Para hacer la solicitud con la librería Axios y mostrar los resultados utilizando Vue.js, primero debes asegurarte de incluir tanto Axios como Vue.js en tu proyecto (puedes usar CDNs o instalar las dependencias mediante npm). Luego, puedes crear una instancia de Vue y utilizar las capacidades de Vue para actualizar la interfaz de usuario. Aquí tienes un ejemplo de cómo hacerlo:


html

Copy code

<!DOCTYPE html>

<html lang="es">

<head>

    <meta charset="UTF-8">

    <title>Tabla de resultados</title>

</head>

<body>


<div id="app">

    <table>

        <thead>

            <tr>

                <th>Nombre</th>

                <th>Dni</th>

            </tr>

        </thead>

        <tbody>

            <tr v-for="resultado in resultados" :key="resultado.id">

                <td>{{ resultado.nombre }}</td>

                <td>{{ resultado.dni }}</td>

            </tr>

        </tbody>

    </table>

</div>


<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js"></script>

<script>

    new Vue({

        el: '#app',

        data: {

            resultados: []

        },

        mounted() {

            axios.get('buscar.php')

                .then(response => {

                    this.resultados = response.data;

                })

                .catch(error => {

                    alert('Hubo un error al cargar los datos.');

                });

        }

    });

</script>


</body>

</html>

Este código utiliza Axios para hacer una solicitud GET a "buscar.php", y Vue.js para manejar los datos y renderizarlos en la tabla. La instancia de Vue se monta en el elemento con el ID "app". Los resultados obtenidos se almacenan en la propiedad "resultados" de la instancia de Vue, y se utiliza la directiva v-for para recorrer los resultados y mostrarlos en la tabla. En caso de que ocurra un error durante la solicitud, se muestra una alerta.





User

agregar boton para cargar tabla con el ejemplo de axion y vuejs

ChatGPT

Si deseas agregar un botón para cargar la tabla utilizando Axios y Vue.js, puedes hacerlo de la siguiente manera:


html

Copy code

<!DOCTYPE html>

<html lang="es">

<head>

    <meta charset="UTF-8">

    <title>Tabla de resultados</title>

</head>

<body>


<div id="app">

    <button @click="cargarDatos">Cargar Tabla</button>

    <table v-if="mostrarTabla">

        <thead>

            <tr>

                <th>Nombre</th>

                <th>Dni</th>

            </tr>

        </thead>

        <tbody>

            <tr v-for="resultado in resultados" :key="resultado.id">

                <td>{{ resultado.nombre }}</td>

                <td>{{ resultado.dni }}</td>

            </tr>

        </tbody>

    </table>

    <div v-else>

        <p>Presiona el botón para cargar la tabla</p>

    </div>

</div>


<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js"></script>

<script>

    new Vue({

        el: '#app',

        data: {

            resultados: [],

            mostrarTabla: false

        },

        methods: {

            cargarDatos() {

                axios.get('buscar.php')

                    .then(response => {

                        this.resultados = response.data;

                        this.mostrarTabla = true;

                    })

                    .catch(error => {

                        alert('Hubo un error al cargar los datos.');

                    });

            }

        }

    });

</script>


</body>

</html>

En este ejemplo, se agregó un botón que ejecuta el método cargarDatos cuando se hace clic en él. El método cargarDatos realiza la solicitud Axios y actualiza la propiedad resultados de la instancia de Vue con los datos obtenidos. Además, se utiliza la propiedad mostrarTabla para controlar si la tabla se muestra o se muestra un mensaje indicando que se debe presionar el botón para cargar la tabla.


La directiva v-if se utiliza para mostrar u ocultar la tabla dependiendo del valor de mostrarTabla. De esta manera, la tabla se mostrará después de hacer clic en el botón para cargar los datos.


hacer como el  primer ejemplo pero con XMLHttpRequest()

ChatGPT

Claro, aquí tienes una versión del ejemplo utilizando XMLHttpRequest() para realizar la solicitud AJAX y actualizar la tabla:


html

Copy code

<!DOCTYPE html>

<html lang="es">

<head>

    <meta charset="UTF-8">

    <title>Tabla de resultados</title>

</head>

<body>


<table>

    <thead>

        <tr>

            <th>Nombre</th>

            <th>Dni</th>

        </tr>

    </thead>

    <tbody id="resultados">

    </tbody>

</table>


<button id="cargarTabla">Cargar Tabla</button>


<script>

    document.getElementById('cargarTabla').addEventListener('click', function() {

        var xhr = new XMLHttpRequest();

        xhr.open('GET', 'buscar.php', true);

        xhr.onreadystatechange = function() {

            if (xhr.readyState === 4) {

                if (xhr.status === 200) {

                    var resultados = JSON.parse(xhr.responseText);

                    mostrarResultados(resultados);

                } else {

                    alert('Hubo un error al cargar los datos.');

                }

            }

        };

        xhr.send();

    });


    function mostrarResultados(resultados) {

        var tbody = document.getElementById('resultados');

        tbody.innerHTML = '';


        resultados.forEach(function(resultado) {

            var fila = document.createElement('tr');

            var nombreCell = document.createElement('td');

            var dniCell = document.createElement('td');


            nombreCell.textContent = resultado.nombre;

            dniCell.textContent = resultado.dni;


            fila.appendChild(nombreCell);

            fila.appendChild(dniCell);


            tbody.appendChild(fila);

        });

    }

</script>


</body>

</html>

En este ejemplo, utilizamos el método XMLHttpRequest() para realizar la solicitud GET a "buscar.php". Cuando el botón "Cargar Tabla" se hace clic, se inicia la solicitud, y una vez que se completa, los resultados obtenidos se pasan a la función mostrarResultados, que actualiza la tabla con los datos obtenidos. Si hay algún problema durante la solicitud, se muestra una alerta de error.


<button id="cargarTabla">Cargar Tabla</button>


<table>

    <thead>

        <tr>

            <th>Nombre</th>

            <th>Dni</th>

        </tr>

    </thead>

    <tbody id="datosfilas">

    </tbody>

</table>




<script>


document.getElementById('cargarTabla').addEventListener('click', function() {


        var xhr = new XMLHttpRequest();


        xhr.open('GET', 'api_cargar_tabla.php', true);


        xhr.onreadystatechange = function() {


            if (xhr.readyState === 4) {

                if (xhr.status === 200) {


                    var resultados = JSON.parse(xhr.responseText);


                    mostrarResultados(resultados);


                } else {


                    alert('Hubo un error al cargar los datos.');

                    

                }

            }

        };


        xhr.send();


    });



function mostrarResultados(campo) {


var fdatos = document.getElementById('datosfilas');


var filas='';


for (i in campo){


filas += `<tr>

    

    <td>${campo[i].nombre}</td>

    <td>${campo[i].dni}</td>

    

</tr>`; 


}


fdatos.innerHTML = filas;


}


</script>

Comentarios

Entradas populares de este blog

INSERTAR Y UPDATE FECHA CON PHP MYSQL EN FORMULARIO METODO POST CON JQUERY ETIQUETA DATE

Copia de Seguridad de Archivo MS Access (.mdb) a Pendrive con VB6

CONVERTIR IMÁGEN JPG O PNG A WEBP CON PHP DE FORMA SIMPLE