Ajax Delete Records From Database Tutorial in PHP

 <?php

$servername = "localhost";
$username = "root";
$password = "";
$database = "test";

// Create Connection
$conn = new mysqli($servername, $username, $password, $database);

// Check Connection
if($conn->connect_error) {
    die("Connection Failed : " . $conn->connect_error);
}
?>
Above File is mysqli_conn.php File





Below File is show-data.php File
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Show Data</title>
</head>
<body>
    <table id="main" border="0" cellspacing="0">
        <tr>
            <td id="header">
                <h1>PHP with Ajax</h1>
            </td>
        </tr>
        <tr>
            <td id="table-load">
                <input type="button" id="load-button" value="Load Data">
            </td>
        </tr>
        <tr>
            <td id="table-data">
                <table border="1" width="100%" cellspacing="0" cellpadding="10px">
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                    </tr>
                    <tr>
                        <td align="center">1</td>
                        <td>Hello World</td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
    <script type="text/javascript" src="js/jquery-3.7.1.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function(){
            $("#load-button").on("click",function(){
                $.ajax({
                    url: "ajax-load.php",
                    type: "POST",
                    success: function(data){
                        $("#table-data").html(data);
                    }
                });
            });
        });
    </script>
</body>
</html>





Below File is insert_data.php File
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="css/style.css">
    <title>Insert Data</title>
</head>
<body>
    <table id="main" border="0" cellspacing="0">
        <tr>
            <td id="header">
                <h1>Add Records with PHP & Ajax</h1>
            </td>
        </tr>
        <tr>
            <td id="table-form">
                <form id="addForm">
                    First Name : <input type="text" id="fname">
                    Last Name : <input type="text" id="lname">
                    <input type="submit" id="save-button" value="Save">
                </form>
            </td>
        </tr>
        <tr>
            <td id="table-data">
            </td>
        </tr>
    </table>
    <div id="error-message"></div>
    <div id="success-message"><div>
    <script type="text/javascript" src="js/jquery-3.7.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            // Load Table Records
            function loadTable(){
                $.ajax({
                url: "ajax-load.php",
                type: "POST",
                success: function(data){
                    $("#table-data").html(data);
                }
            });
            }
            loadTable();    //Load Table Records on Page Load

            // Insert New Records
            $("#save-button").on("click",function(e){
                e.preventDefault();
                var fname = $("#fname").val();
                var lname = $("#lname").val();
                if(fname == "" || lname == "") {
                    $("#error-message").html("All fields are required").slideDown();
                    $("#success-message").slideUp();
                } else {
                    $.ajax({
                    url: "ajax_insert.php",
                    type: "POST",
                    data: {first_name:fname, last_name:lname},
                    success: function(data){
                        if(data == 1) {
                            loadTable();
                            $("#addForm").trigger("reset");
                            $("#success-message").html("Data Inserted Successfully.").slideDown();
                            $("#error-message").slideUp();
                        } else {
                            $("#error-message").html("Can't Save Record.").slideDown();
                            $("#success-message").slideUp();
                        }
                    }
                });
                }
            });

            $(document).on("click",".delete-btn",function(){
                if(confirm("Do you really want to delete this record ?")) {
                    var studentId = $(this).data("id");
                    var element = this;
               
                    $.ajax({
                        url: "ajax-delete.php",
                        type: "POST",
                        data: {id:studentId},
                        success: function(data){
                            if(data == 1) {
                                $(element).closest("tr").fadeOut();
                            } else {
                                $("#error-message").html("Can't Delete Record.").slideDown();
                                $("#success-message").slideUp();
                            }
                        }
                    });
                }
            });
        });
    </script>
</body>
</html>





Below File is ajax-load.php File
<?php
include("mysqli_conn.php");

$sql = "SELECT * FROM students";
$result = $conn->query($sql);
$output = "";
if($result->num_rows > 0) {
    $output = "<table border='1' width='100%' cellspacing='0' cellpadding='10px'>
                <tr>
                    <th width='100px'>Id</th>
                    <th>Name</th>
                    <th width='100px'>Delete</th>
                </tr>";
    while($row = $result->fetch_assoc()) {
        $output .= "<tr><td>{$row["id"]}</td><td>{$row["first_name"]} {$row["last_name"]}</td><td><button class='delete-btn' data-id='{$row["id"]}'>Delete</button></td></tr>";
    }
    $output .= "</table>";
    echo $output;
} else {
    echo "<h2>No Record Found.</h2>";
}
$conn->close();
?>





Below File is ajax-delete.php File
<?php
$student_id = $_POST["id"];

include("mysqli_conn.php");

$sql = "DELETE FROM students WHERE id = {$student_id}";

if($conn->query($sql) == TRUE) {
    echo 1;
} else {
    echo 0;
}
?>





Below File is ajax_insert.php File
<?php
$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];

include("mysqli_conn.php");

$sql = "INSERT INTO students(first_name,last_name) VALUES('{$first_name}','{$last_name}')";

if($conn->query($sql) == TRUE) {
    echo 1;
} else {
    echo 0;
}
?>





Below File is css/style.css File
body {
    font-family: arial;
    background: #b2bec3;
    padding: 0;
    margin: 0;
}

h1 {
    text-align: center;
    margin: 15px;
}

#main {
    width: 800px;
    margin: 0 auto;
    background: #ffffff;
    font-size: 19px;
}

#header {
    background: #f7d794;
}

#table-form {
    background: #55efc4;
    padding: 20px 10px;
}

#table-data {
    padding: 15px;
    height: 500px;
    vertical-align: top;
}

#table-data th {
    background: #74b9ff;
}

#table-data tr:nth-child(odd) {
    background: #ecf0f1;
}

#success-message {
    background: #DEF1D8;
    color: #008000;
    padding: 10px;
    margin: 10px;
    display: none;
    position: absolute;
    right: 15px;
    top: 15px;
}

#error-message {
    background: #EFDCDD;
    color: #ff0000;
    padding: 10px;
    margin: 10px;
    display: none;
    position: absolute;
    right: 15px;
    top: 15px;
}

.delete-btn {
    background: #ff0000;
    color: #ffffff;
    border: 0;
    padding: 4px 10px;
    border-radius: 3px;
}


Comments

Popular posts from this blog

GROUP BY Clause and HAVING Clause in PHP

Method Overriding in Traits in PHP

Mysqli database Connection and Display Table Data from Database