Ejercicio actores pseudo autocompletar

<!DOCTYPE html>

<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    </head>
    <body>
        Actor:<input type="text" id="actor"><br/>
        <div id="lista"></div>
        <script>
            $(function () {
                console.log("Página cargada");
                $('#actor').keyup(function () {
                    console.log("Pulsado");
                    fetch('fetch_backend.php?actor='+$('#actor').val(), {
                        method: 'GET',
                    })
                            .then(function (response) {
                                console.log(response);
                                return response.json();
                            })
                            .then(function (data) {
                                console.log('data = ', data);
                                $('#lista').html('');
                                for(i=0;i<data.length;i++){
                                    $('#lista').append(data[i]+"<br>");
                                }
                            })
                            .catch(function (err) {
                                console.error(err);
                            });
                });
            });
        </script>
    </body>
</html>

<?php

$server = "localhost";
$user = "root";
$password = "";
$db = "sakila";
try {
    $conn = new PDO("mysql:host=$server;dbname=$db;charset=UTF8", $user, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $actor = filter_input(INPUT_GET, "actor");
    $sql = "select * from actor "
            . "where first_name like :actor "
            . "or last_name like :actor limit 10";
    $parametros = [
        'actor' => '%' . $actor . '%'
    ];
    $st = $conn->prepare($sql);
    $st->execute($parametros);
    $resultado = [];
    while ($fila = $st->fetch()) {
        $resultado[] = $fila['first_name'] . " " . $fila['last_name'];
    }
    echo json_encode($resultado);
} catch (Exception $e) {
    echo "Connection failed: " . $e->getMessage();
}

Publicado por

Juan Pablo Fuentes

Formador de programación y bases de datos