DEV Community

codeanddeploy
codeanddeploy

Posted on

Edit or Update Data with Bootstrap Modal in PHP & MySQL Using Ajax

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/php/edit-or-update-data-with-bootstrap-modal-in-php-mysql-using-ajax

In this code, we will show you how to display the data with Bootstrap Modal and Update it in PHP & MySQL using AJAX. This function is one of the most important functions when creating an application. So we hope that you found it helpful to your research.

Alt text of image

Index.html

First, we need to create our index.html just check the below code.

<!doctype html>
<html lang="en">
<head>
    <title>Edit or Update Data Using PHP & MySQL Ajax</title>

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

    <!-- Page CSS -->
    <link rel="stylesheet" href="assets/css/styles.css">
</head>

<body>

    <div class="container">

        <br><br>

        <h1>Edit or Update Data Using PHP & MySQL Ajax</h1>

        <br><br>

        <div class="row">
            <div class="col-md-4">
                <h3>Add New Employee</h3>

                <form action="save.php" id="form">
                    <div class="form-group">
                        <label for="email">Email</label>
                        <input class="form-control" type="text" name="email">
                    </div>
                    <div class="form-group">
                        <label for="first_name">First Name</label>
                        <input class="form-control" type="text" name="first_name">
                    </div>
                    <div class="form-group">
                        <label for="last_name">Last Name</label>
                        <input class="form-control" type="text" name="last_name">
                    </div>
                    <div class="form-group">
                        <label for="address">Address</label>
                        <textarea class="form-control" type="text" name="address" rows="3"></textarea>
                    </div>
                    <button type="button" class="btn btn-primary" id="btnSubmit">Submit</button>
                </form>
            </div>

            <div class="col-md-8">
                <h3>List of Employees</h3>
                <div id="employees-list"></div>
            </div>
        </div>
    </div>

    <!-- The Modal -->
    <div class="modal" id="edit-employee-modal">
        <div class="modal-dialog">
            <div class="modal-content">

                <!-- Modal Header -->
                <div class="modal-header">
                    <h4 class="modal-title">Edit Employee</h4>
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                </div>

                <!-- Modal body -->
                <div class="modal-body">
                    <form action="update.php" id="edit-form">
                        <input class="form-control" type="hidden" name="id">
                        <div class="form-group">
                            <label for="email">Email</label>
                            <input class="form-control" type="text" name="email">
                        </div>
                        <div class="form-group">
                            <label for="first_name">First Name</label>
                            <input class="form-control" type="text" name="first_name">
                        </div>
                        <div class="form-group">
                            <label for="last_name">Last Name</label>
                            <input class="form-control" type="text" name="last_name">
                        </div>
                        <div class="form-group">
                            <label for="address">Address</label>
                            <textarea class="form-control" type="text" name="address" rows="3"></textarea>
                        </div>
                        <button type="button" class="btn btn-primary" id="btnUpdateSubmit">Update</button>
                        <button type="button" class="btn btn-danger float-right" data-dismiss="modal">Close</button>
                    </form>


                </div>

            </div>
        </div>
    </div>


    <!-- Must put our javascript files here to fast the page loading -->

    <!-- jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <!-- Popper JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <!-- Bootstrap JS -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <!-- Page Script -->
    <script src="assets/js/scripts.js"></script>

</body>

</html>
Enter fullscreen mode Exit fullscreen mode

Save.php

After the above code so we need the save function so that we can enable to add a new record.

<?php
    $request = $_REQUEST; //a PHP Super Global variable which used to collect data after submitting it from the form
    $email = $request['email']; //get the date of birth from collected data above
    $first_name = $request['first_name']; //get the date of birth from collected data above
    $last_name = $request['last_name'];
    $address = $request['address'];

    $servername = "localhost"; //set the servername
    $username = "root"; //set the server username
    $password = ""; // set the server password (you must put password here if your using live server)
    $dbname = "demos"; // set the table name

    $mysqli = new mysqli($servername, $username, $password, $dbname);

    if ($mysqli->connect_errno) {
      echo "Failed to connect to MySQL: " . $mysqli->connect_error;
      exit();
    }

    // Set the INSERT SQL data
    $sql = "INSERT INTO employees (email, first_name, last_name, address)
    VALUES ('".$email."', '".$first_name."', '".$last_name."', '".$address."')";

    // Process the query so that we will save the date of birth
    if ($mysqli->query($sql)) {
      echo "Employee has been successfully created.";
    } else {
      return "Error: " . $sql . "<br>" . $mysqli->error;
    }

    // Close the connection after using it
    $mysqli->close();
?>
Enter fullscreen mode Exit fullscreen mode

All.php

Our next code is about getting all records via ajax.

<?php
    $servername = "localhost"; //set the servername
    $username = "root"; //set the server username
    $password = ""; // set the server password (you must put password here if your using live server)
    $dbname = "demos"; // set the table name

    $mysqli = new mysqli($servername, $username, $password, $dbname);

    if ($mysqli->connect_errno) {
      echo "Failed to connect to MySQL: " . $mysqli->connect_error;
      exit();
    }

    // Set the INSERT SQL data
    $sql = "SELECT * FROM employees";

    // Process the query so that we will save the date of birth
    $results = $mysqli->query($sql);

    // Fetch Associative array
    $row = $results->fetch_all(MYSQLI_ASSOC);

    // Free result set
    $results->free_result();

    // Close the connection after using it
    $mysqli->close();

    echo json_encode($row);
?>
Enter fullscreen mode Exit fullscreen mode

Get.php

In this code, we will get the record and display it via modal.

<?php
    $request = $_REQUEST; //a PHP Super Global variable which used to collect data after submitting it from the form
    $employeeId = $request['employee_id'];//define the employee ID

    $servername = "localhost"; //set the servername
    $username = "root"; //set the server username
    $password = ""; // set the server password (you must put password here if your using live server)
    $dbname = "demos"; // set the table name

    $mysqli = new mysqli($servername, $username, $password, $dbname);

    if ($mysqli->connect_errno) {
      echo "Failed to connect to MySQL: " . $mysqli->connect_error;
      exit();
    }

    // Set the INSERT SQL data
    $sql = "SELECT * FROM employees WHERE id='".$employeeId."'";

    // Process the query so that we will save the date of birth
    $results = $mysqli->query($sql);

    // Fetch Associative array
    $row = $results->fetch_assoc();

    // Free result set
    $results->free_result();

    // Close the connection after using it
    $mysqli->close();

    echo json_encode($row);
?>
Enter fullscreen mode Exit fullscreen mode

Update.php

Now in this code, we are enabled to update the record after clicking the "Update" button via modal using ajax.

<?php
    $request = $_REQUEST; //a PHP Super Global variable which used to collect data after submitting it from the form
    $id = $request['id']; //employee ID we are using it to get the employee record
    $email = $request['email']; //get the date of birth from collected data above
    $first_name = $request['first_name']; //get the date of birth from collected data above
    $last_name = $request['last_name'];
    $address = $request['address'];

    $servername = "localhost"; //set the servername
    $username = "root"; //set the server username
    $password = ""; // set the server password (you must put password here if your using live server)
    $dbname = "demos"; // set the table name

    $mysqli = new mysqli($servername, $username, $password, $dbname);

    if ($mysqli->connect_errno) {
      echo "Failed to connect to MySQL: " . $mysqli->connect_error;
      exit();
    }

    // Set the INSERT SQL data
    $sql = "UPDATE employees SET email='".$email."', first_name='".$first_name."', last_name='".$last_name."', address='".$address."' WHERE id='".$id."'";

    // Process the query so that we will save the date of birth
    if ($mysqli->query($sql)) {
      echo "Employee has been sucessfully updated.";
    } else {
      return "Error: " . $sql . "<br>" . $mysqli->error;
    }

    // Close the connection after using it
    $mysqli->close();
?>
Enter fullscreen mode Exit fullscreen mode

Scripts.js

In this code, we are enabled to process the above PHP codes via AJAX from saving record, getting all records, retrieving records, and updating it.

function all() 
{
    // Ajax config
    $.ajax({
        type: "GET", //we are using GET method to get all record from the server
        url: 'all.php', // get the route value
        success: function (response) {//once the request successfully process to the server side it will return result here

            // Parse the json result
            response = JSON.parse(response);

            var html = "";
            // Check if there is available records
            if(response.length) {
                html += '<div class="list-group">';
                // Loop the parsed JSON
                $.each(response, function(key,value) {
                    // Our employee list template
                    html += '<a href="#" class="list-group-item list-group-item-action">';
                    html += "<p>" + value.first_name +' '+ value.last_name + " <span class='list-email'>(" + value.email + ")</span>" + "</p>";
                    html += "<p class='list-address'>" + value.address + "</p>";
                    html += "<button class='btn btn-sm btn-primary mt-2' data-toggle='modal' data-target='#edit-employee-modal' data-id='"+value.id+"'>Edit</button>";
                    html += '</a>';
                });
                html += '</div>';
            } else {
                html += '<div class="alert alert-warning">';
                  html += 'No records found!';
                html += '</div>';
            }



            // Insert the HTML Template and display all employee records
            $("#employees-list").html(html);
        }
    });
}

function save() 
{
    $("#btnSubmit").on("click", function() {
        var $this           = $(this); //submit button selector using ID
        var $caption        = $this.html();// We store the html content of the submit button
        var form            = "#form"; //defined the #form ID
        var formData        = $(form).serializeArray(); //serialize the form into array
        var route           = $(form).attr('action'); //get the route using attribute action

        // Ajax config
        $.ajax({
            type: "POST", //we are using POST method to submit the data to the server side
            url: route, // get the route value
            data: formData, // our serialized array data for server side
            beforeSend: function () {//We add this before send to disable the button once we submit it so that we prevent the multiple click
                $this.attr('disabled', true).html("Processing...");
            },
            success: function (response) {//once the request successfully process to the server side it will return result here
                $this.attr('disabled', false).html($caption);

                // Reload lists of employees
                all();

                // We will display the result using alert
                alert(response);

                // Reset form
                resetForm(form);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // You can put something here if there is an error from submitted request
            }
        });
    });
}

function resetForm(selector) 
{
    $(selector)[0].reset();
}


function get() 
{
    $(document).delegate("[data-target='#edit-employee-modal']", "click", function() {

        var employeeId = $(this).attr('data-id');

        // Ajax config
        $.ajax({
            type: "GET", //we are using GET method to get data from server side
            url: 'get.php', // get the route value
            data: {employee_id:employeeId}, //set data
            beforeSend: function () {//We add this before send to disable the button once we submit it so that we prevent the multiple click

            },
            success: function (response) {//once the request successfully process to the server side it will return result here
                response = JSON.parse(response);
                $("#edit-form [name=\"id\"]").val(response.id);
                $("#edit-form [name=\"email\"]").val(response.email);
                $("#edit-form [name=\"first_name\"]").val(response.first_name);
                $("#edit-form [name=\"last_name\"]").val(response.last_name);
                $("#edit-form [name=\"address\"]").val(response.address);
            }
        });
    });
}

function update() 
{
    $("#btnUpdateSubmit").on("click", function() {
        var $this           = $(this); //submit button selector using ID
        var $caption        = $this.html();// We store the html content of the submit button
        var form            = "#edit-form"; //defined the #form ID
        var formData        = $(form).serializeArray(); //serialize the form into array
        var route           = $(form).attr('action'); //get the route using attribute action

        // Ajax config
        $.ajax({
            type: "POST", //we are using POST method to submit the data to the server side
            url: route, // get the route value
            data: formData, // our serialized array data for server side
            beforeSend: function () {//We add this before send to disable the button once we submit it so that we prevent the multiple click
                $this.attr('disabled', true).html("Processing...");
            },
            success: function (response) {//once the request successfully process to the server side it will return result here
                $this.attr('disabled', false).html($caption);

                // Reload lists of employees
                all();

                // We will display the result using alert
                alert(response);

                // Reset form
                resetForm(form);

                // Close modal
                $('#edit-employee-modal').modal('toggle');
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // You can put something here if there is an error from submitted request
            }
        });
    });
}


$(document).ready(function() {

    // Get all employee records
    all();

    // Submit form using AJAX To Save Data
    save();

    // Get the data and view to modal
    get();

    // Updating the data
    update();
});
Enter fullscreen mode Exit fullscreen mode

Styles.css

Then our last code about the custom style of our page.

.list-email {
    font-style: italic;
}

.list-address {
    margin-top: -14px;
    margin-bottom: 0px;
    font-size: 12px;
}
Enter fullscreen mode Exit fullscreen mode

Okay, we were done setting up our code and you can now enable to update/edit your record using ajax. I hope this code can help you.

Download Source Code Here

Discussion (0)