Ajax Delete Records from Database 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 is mysqli_conn.php File which is included in below Files.






Below 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>Student Name</th>
                    <th>Age</th>
                    <th>City</th>
                    <th width='100px'>Delete</th>
                </tr>";
    while ($row = $result->fetch_assoc()) {
        $output .= "<tr><td>{$row['id']}</td><td>{$row['student_name']}</td><td>{$row['age']}</td><td>{$row['city']}</td><td><button class='delete-btn' data-id='{$row['id']}'>Delete</button></td></tr>";
    }
    $output .= "</table>";
    $conn->close();
    echo $output;
} else {
    echo "<h2>No Record Found.</h2>";
}







Below is ajax-insert.php File.
<?php

$stu_name = $_POST["student_name"];
$stu_age = $_POST["student_age"];
$stu_city = $_POST["student_city"];

include("mysqli_conn.php");

$sql = "INSERT INTO students(student_name, age, city) VALUES('{$stu_name}','{$stu_age}','{$stu_city}')";

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







Below 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">
    <script src="jquery-3.7.1.min.js"></script>
</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"><br><br>
            </td>
        </tr>
        <tr>
            <td id="table-data">
            </td>
        </tr>
    </table>
    <script type="text/javascript" src="js/jquery.js"></script>
    <!-- Whenever we use Ajax, there is no need to use <Form> and
     also no need to use method "GET" or "POST" -->
    <script type="text/javascript">
        $(document).ready(function() {
            $("#load-button").on("click", function(e) {
                $.ajax({
                    url: "ajax-load.php",
                    type: "POST",
                    success: function(data) {
                        $("#table-data").html(data);
                    }
                });
            });
        });
    </script>
</body>

</html>







Below 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 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">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Insert Data</title>
    <style>
        body {
            font-family: arial;
            background: #b2bec3;
            padding: 0;
            margin: 0;
        }

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

        #main {
            width: 800px;
            margin: 0 auto;
            background: white;
            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-color: #ecf0f1;
        }

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

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

        .delete-btn {
            background: red;
            color: #fff;
            border: 0;
            padding: 4px 20px;
            border-radius: 3px;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <table id="main" border="0" cellspacing="0">
        <tr>
            <td id="header">
                <h1>All Records with PHP & Ajax</h1>
            </td>
        </tr>
        <tr>
            <td id="table-form">
                <form id="addForm">
                    Student Name : <input type="text" id="name">&nbsp;&nbsp;&nbsp;&nbsp;
                    Age : <input type="text" id="age">
                    City : <input type="text" id="city">
                    <input type="submit" id="save-button" value="Save"><br><br><br>
                </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 name = $("#name").val();
                var age = $("#age").val();
                var city = $("#city").val();

                if (name == "" || age == "" || city == "") {
                    $("#error-message").html("All Fields are required.").slideDown();
                    $("#success-message").slideUp();
                } else {
                    $.ajax({
                        url: "ajax-insert.php",
                        type: "POST",
                        data: {
                            student_name: name,
                            student_age: age,
                            student_city: city
                        },
                        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>








Comments

Popular posts from this blog

Ajax Insert Records in Database Tutorial in PHP

SubQuery with EXISTS and NOT EXISTS in PHP

Submitting HTML Form data in JSON File (without MySql Database) in PHP