CRUD AJAX

actores_ajax (html)

<!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>
        <script src="actores.js" type="text/javascript"></script>
    </head>

    <body>
        <p>Nombre<input type="text" id="first_name" name="first_name"></p>
        <p>Apellidos<input type="text"  id="last_name" name="last_name"></p>
        <input type="button" value="Añadir" id="nuevo">
        <div id="mensaje"></div>
        <div id="lista"></div>
    </body>
</html>

actores.js (ajax)

$(function () {
    cargar();
    function cargar() {
        $.get("actores_ajax_back.php?funcion=lista", function (data) {
            $("#lista").html(data);
            $(".borrar").click(function () {
                console.log($(this));
                console.log($(this).val());
                $.post("actores_ajax_back.php?funcion=borrar",
                        {actor_id: $(this).val()})
                        .done(function (data) {
                            console.log(data);
                            $('#mensaje').html("Borrado");
                            cargar();
                        });
            });
        });
    }
    $("#nuevo").click(function () {
        $.post("actores_ajax_back.php?funcion=nuevo",
                {first_name: $('#first_name').val(), last_name: $('#last_name').val()})
                .done(function (data) {
                    $('#mensaje').html("Insertado con id " + data);
                    cargar();
                });
    });

});

actores_ajax_back.php (backend)

<?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);
} catch (Exception $e) {
    echo "Connection failed: " . $e->getMessage();
}
$funcion = filter_input(INPUT_GET, "funcion");

if (function_exists($funcion)) {
    $funcion($conn);
}

function lista($conn) {
    try {
        $sql = "select * from actor";
        $q = $conn->query($sql);
        ?>
        <table>
            <tr><td>Id</td><td>Nombre</td><td>Apellido</td><td>Acciones</td>
            </tr>
            <?php
            while ($row = $q->fetch()) {
                ?> 
                <tr><td><?= $row['actor_id'] ?></td>
                    <td><?= $row['first_name'] ?></td>
                    <td><?= $row['last_name'] ?></td>
                    <td><button class="borrar" value="<?= $row['actor_id'] ?>">Borrar</button></td>
                </tr>
                <?php
            }
            ?></table><?php
    } catch (Exception $ex) {
        echo $ex->getMessage();
    }
}

function nuevo($conn) {
    try {
        $first_name = filter_input(INPUT_POST, "first_name", FILTER_SANITIZE_MAGIC_QUOTES);
        $last_name = filter_input(INPUT_POST, "last_name", FILTER_SANITIZE_MAGIC_QUOTES);
        if (!empty($first_name) && !empty($last_name)) {
            $sql = "insert into actor(first_name,last_name) values ('$first_name','$last_name')";
            //Ejecutarlo
            if ($conn->exec($sql) > 0) {
                echo $conn->lastInsertId();
            }
        }
    } catch (Exception $ex) {
        echo $ex->getMessage();
    }
}
function borrar($conn) {
    try {
        $actor_id = filter_input(INPUT_POST, "actor_id");
         if (!empty($actor_id) ) {
            $sql = "delete from actor where actor_id=$actor_id";
            //Ejecutarlo
            echo $conn->exec($sql);
        }
    } catch (Exception $ex) {
        echo $ex->getMessage();
    }
}

Publicado por

Juan Pablo Fuentes

Formador de programación y bases de datos