Ajax Complete CRUD Operation in PHP

 <?php

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

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

// 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">
            </td>
        </tr>
    </table>

    <script type="text/javascript" src="js/jquery-3.7.1.min.js"></script>

    <script type="text/javascript">
        // When we use Ajax, at that time we don't need to use Form and if we use Form then we don't need to specity "method=POST OR GET"
        $(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">
    <title>Insert Data</title>
    <link rel="stylesheet" href="css/style.css">
</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">
                    Student Name : <input type="text" id="sname"><br>
                    Age : <input type="text" id="age" style="margin-left: 88px"><br>
                    City : <input type="text" id="city" style="margin-left: 88px"><br>
                    <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>
    <div id="modal">
        <div id="modal-form">
            <h2>Edit Form</h2>
            <table cellpadding="10px" width="100%">

            </table>
            <div id="close-btn">X</div>
        </div>
    </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 sname = $("#sname").val();
                var age = $("#age").val();
                var city = $("#city").val();
                if (sname == "" || age == "" || city == "") {
                    $("#error-message").html("All fields are required.").slideDown();
                    $("#success-message").slideUp();
                } else {
                    $.ajax({
                        url: "ajax-insert.php",
                        type: "POST",
                        data: {
                            student_name: sname,
                            age: age,
                            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();
                            }
                        }
                    });
                }
            });

            // Below Delete Button will dynamically Load so for apply Event, below is the correct way :
            // Delete Records
            $(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();
                            }
                        }
                    });
                }
            });

            // Show Modal Box
            $(document).on("click", ".edit-btn", function() {
                $("#modal").show();
                var studentId = $(this).data("eid");

                $.ajax({
                    url: "load-update-form.php",
                    type: "POST",
                    data: {
                        id: studentId
                    },
                    success: function(data) {
                        $("#modal-form table").html(data);
                    }
                });
            });

            // Hide Moda Box
            $("#close-btn").on("click", function() {
                $("#modal").hide();
            });

            // Save Update Form
            $(document).on("click", "#edit-submit", function() {
                var stuId = $("#edit-id").val();
                var stuname = $("#edit-sname").val();
                var stuage = $("#edit-age").val();
                var stucity = $("#edit-city").val();

                $.ajax({
                    url: "ajax-update-form.php",
                    type: "POST",
                    data: {
                        id: stuId,
                        student_name: stuname,
                        student_age: stuage,
                        student_city: stucity
                    },
                    success: function(data) {
                        if (data == 1) {
                            $("#modal").hide();
                            loadTable();
                        }
                    }
                });
            });
        });
    </script>
</body>

</html>





Below File is load-update-form.php File
<?php
$student_id = $_POST["id"];

include("mysqli_conn.php");

$sql = "SELECT * FROM students WHERE id = {$student_id}";
$result = $conn->query($sql);
$output = "";
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $output .= "<tr>
                    <td>Student Name</td>
                    <td>
                        <input type='text' id='edit-sname' value='{$row["student_name"]}'>
                        <input type='text' id='edit-id' hidden value='{$row["id"]}'>
                    </td>
                </tr>
                <tr>
                    <td>Age</td>
                    <td><input type='text' id='edit-age' value='{$row["age"]}'></td>
                </tr>
                <tr>
                    <td>City</td>
                    <td><input type='text' id='edit-city' value='{$row["city"]}'></td>
                </tr>
                <tr>
                    <td></td>
                    <td><input type='submit' id='edit-submit' value='save'></td>
                </tr>";
    }
    echo $output;
} else {
    echo "<h2>No Record Found.</h2>";
}
$conn->close();





Below File is ajax-update-form.php File
<?php
$id = $_POST["id"];
$studentName = $_POST["student_name"];
$age = $_POST["student_age"];
$city = $_POST["student_city"];

include("mysqli_conn.php");

$sql = "UPDATE students SET student_name='{$studentName}',age='{$age}',city='{$city}' WHERE id='{$id}'";

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





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>Student Name</th>
                    <th>Age</th>
                    <th>City</th>
                    <th width='90px'>Edit</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 align='center'><button class='edit-btn' data-eid='{$row["id"]}'>Edit</button></td><td align='center'><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-insert.php File
<?php
$student_name = $_POST["student_name"];
$age = $_POST["age"];
$city = $_POST["city"];

include("mysqli_conn.php");

$sql = "INSERT INTO students(student_name, age, city) VALUES('$student_name','$age','$city')";

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





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 css/style.css File
body {
    font-family: arial;
    background: #909090;
    padding: 0;
    margin: 0;
}

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

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

#header {
    background: #f7d794;
}

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

#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: #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;
}

#save-button {
    background-color: #000000;
    color: #ffffff;
    border-radius: 8px;
    cursor: pointer;
    padding: 10px 40px;
    margin: 10px 130px;
}

.delete-btn {
    background: #ff0000;
    color: #ffffff;
    border: 0;
    padding: 5px 20px;
    border-radius: 3px;
    cursor: pointer;
}

.edit-btn {
    background: #27ae60;
    color: #ffffff;
    border: 0;
    padding: 5px 20px;
    border-radius: 3px;
    cursor: pointer;
}

#modal {
    background: rgba(0, 0, 0, 0.7);
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    z-index: 100;
    display: none;
}

#modal-form {
    background: #ffffff;
    width: 40%;
    position: relative;
    top: 20%;
    left: calc(30%);
    padding: 15px;
    border-radius: 4px;
}

#modal-form h2 {
    /* margin: top - right and left - bottom */
    margin: 0 0 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #000;
}

#close-btn {
    background: #ff0000;
    color: #ffffff;
    width: 30px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    border-radius: 50%;
    position: absolute;
    top: -15px;
    right: -15px;
    cursor: pointer;
}



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