-1

I have put together a webpage which has a top fixed navbar and a CRUD datatable with pagination which has buttons to open up modals. The issue that I seem to be having is that when I click the delete button the modal pops up and I am able to delete the record however the modal does not close unless I click somewhere else outside the modal and to add to this the total records "Showing 10 of 12" is incorrect until I refresh the page then the correct value is shown. ` I have included all my code below. I am not sure how to solve this problem any assistance would be highly appreciated.

    //AJAX CODE
    //ADD
    $(document).on('click','#btn-add',function(e) {
        var data = $("#user_form").serialize();
        $.ajax({
            data: data,
            type: "post",
            url: "backend/save.php",
            success: function(dataResult){
                    var dataResult = JSON.parse(dataResult);
                    if(dataResult.statusCode==200){
                        $('#addEmployeeModal').modal('hide');
                        alert('Data added successfully !'); 
                        location.reload();                      
                    }
                    else if(dataResult.statusCode==201){
                       alert(dataResult);
                    }
            }
        });
    });
    $(document).on('click','.update',function(e) {
        var id=$(this).attr("data-id");
        var code=$(this).attr("data-code");
        var regno=$(this).attr("data-regno");
        var vatno=$(this).attr("data-vatno");
        var name=$(this).attr("data-name");
        var address=$(this).attr("data-address");
        var phone=$(this).attr("data-phone");
        var email=$(this).attr("data-email");       
        var person=$(this).attr("data-person");
        $('#id_u').val(id);
        $('#code_u').val(code);
        $('#regno_u').val(regno);
        $('#vatno_u').val(vatno);
        $('#name_u').val(name);
        $('#address_u').val(address);
        $('#phone_u').val(phone);
        $('#email_u').val(email);       
        $('#person_u').val(person);
    });
    //Update
    $(document).on('click','#update',function(e) {
        var data = $("#update_form").serialize();
        $.ajax({
            data: data,
            type: "post",
            url: "backend/save.php",
            success: function(dataResult){
                    var dataResult = JSON.parse(dataResult);
                    if(dataResult.statusCode==200){
                        $('#editEmployeeModal').modal('hide');
                        alert('Data updated successfully !'); 
                        location.reload();                      
                    }
                    else if(dataResult.statusCode==201){
                       alert(dataResult);
                    }
            }
        });
    });
    $(document).on("click", ".delete", function() { 
        var id=$(this).attr("data-id");
        $('#id_d').val(id);
        
    });
    $(document).on("click", "#delete", function() { 
        $.ajax({
            url: "backend/save.php",
            type: "POST",
            cache: false,
            data:{
                type:3,
                id: $("#id_d").val()
            },
            success: function(dataResult){
                    $('#deleteEmployeeModal').modal('hide');
                    $("#"+dataResult).remove();
            
            }
        });
    });
    $(document).on("click", "#delete_multiple", function() {
        var user = [];
        $(".user_checkbox:checked").each(function() {
            user.push($(this).data('user-id'));
        });
        if(user.length <=0) {
            alert("Please select records."); 
        } 
        else { 
            WRN_PROFILE_DELETE = "Are you sure you want to delete "+(user.length>1?"these":"this")+" row?";
            var checked = confirm(WRN_PROFILE_DELETE);
            if(checked == true) {
                var selected_values = user.join(",");
                console.log(selected_values);
                $.ajax({
                    type: "POST",
                    url: "backend/save.php",
                    cache:false,
                    data:{
                        type: 4,                        
                        id : selected_values
                    },
                    success: function(response) {
                        var ids = response.split(",");
                        for (var i=0; i < ids.length; i++ ) {   
                            $("#"+ids[i]).remove(); 
                        }   
                    } 
                }); 
            }  
        } 
    });
    $(document).ready(function(){
        $('[data-toggle="tooltip"]').tooltip();
        var checkbox = $('table tbody input[type="checkbox"]');
        $("#selectAll").click(function(){
            if(this.checked){
                checkbox.each(function(){
                    this.checked = true;                        
                });
            } else{
                checkbox.each(function(){
                    this.checked = false;                        
                });
            } 
        });
        checkbox.click(function(){
            if(!this.checked){
                $("#selectAll").prop("checked", false);
            }
        });
    });

//MY php CODE
<?php
session_start();
if (!isset($_SESSION["user_email"])) {
  header('location: login.html');
}
include 'backend/database.php';
?>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>
    PHP
  </title>
  <!-- favicon -->
  <link rel="icon" href="/assets/img/favicon.ico">
  <!-- ===== DATATABLE ===== -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.2/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css" />
  <!-- Font Awesome -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css">
  <!-- ===== DATATABLE STYLE ===== -->
  <link rel="stylesheet" href="http://localhost/PHP/assets/style.css">
  <!-- Style -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.2/dist/js/bootstrap.bundle.min.js"></script>
  <!-- BOOTSTRAP MODAL -->
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
  <!-- AJAX -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="ajax/ajax.js"></script>
</head>

<body class="home">
  <!-- Navbar -->
  <header class="header">
    <nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top">
      <div class="container-fluid">
        <a class="navbar-brand" href="#">LIMA RDF <i>Engineering</i></a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
          <span></span>
          <span></span>
          <span></span>
        </button>
        <div class="collapse navbar-collapse justify-content-between" id="navbarSupportedContent">
          <ul class="navbar-nav" style="margin-left: auto;text-align: center;">
            <li class="nav-item">
              <a class="nav-link" aria-current="page" href="http://localhost/PHP/index.php">Home</a>
            </li>

            <li class="nav-item dropdown">
              <a class="nav-link active dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                Setup
              </a>
              <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
                <li><a class="dropdown-item" href="http://localhost/PHP/partner.php">Business Partner</a></li>
                <li><a class="dropdown-item" href="#">Project</a></li>
                <li><a class="dropdown-item" href="#">Something else here</a></li>
              </ul>
            </li>
            <li class="nav-item dropdown">
              <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                Dropdown
              </a>
              <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
                <li><a class="dropdown-item" href="#">Action</a></li>
                <li><a class="dropdown-item" href="#">Another action</a></li>
                <li>
                  <hr class="dropdown-divider">
                </li>
                <li><a class="dropdown-item" href="#">Something else here</a></li>
              </ul>
            </li>
            <li class="nav-item dropdown">
              <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                Dropdown
              </a>
              <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
                <li><a class="dropdown-item" href="#">Action</a></li>
                <li><a class="dropdown-item" href="#">Another action</a></li>
                <li>
                  <hr class="dropdown-divider">
                </li>
                <li><a class="dropdown-item" href="#">Something else here</a></li>
              </ul>
            </li>
            <li class="nav-item">
              <button class="btn btn-outline-danger" type="button" onclick="window.location.href='./login/logout.php';">Log Out</button>
            </li>
          </ul>
        </div>
      </div>
    </nav>
  </header>
  <!-- DATATABLE START-->
  <div class="container">
  <div>
      <a href="#addClientModal" class="btn btn-success" data-toggle="modal"><i class="material-icons">&#xE147;</i>
        <span>Add New Client</span></a>
    </div>   
    <div class="row">
      <div class="col-md-12">
        <div class="datatable">
          <table id="example" class="content-table table-hover" style="width:100%">
            <thead>
              <tr>
                <th style="text-align: center;">CLIENT NO</th>
                <th>NAME</th>
                <th>ADDRESS</th>
                <th>PHONE NO</th>
                <th>EMAIL</th>
                <th>CONTACT PERSON</th>
                <th style="text-align: center;">ACTION</th>
              </tr>
            </thead>
            <tbody>
              <?php
              $result = mysqli_query($conn, "SELECT * FROM tbl_client");
              $i = 1;
              while ($row = mysqli_fetch_array($result)) {
              ?>
                <tr id="<?php echo $row["id"]; ?>">
                  <td style="text-align: center;"><?php echo $row["code"]; ?></td>
                  <td><?php echo $row["name"]; ?></td>
                  <td><?php echo $row["address"]; ?></td>
                  <td><?php echo $row["phone"]; ?></td>
                  <td><?php echo $row["email"]; ?></td>
                  <td><?php echo $row["person"]; ?></td>

                  <td style="text-align: center;">
                    <a style="padding-left:5px;padding-right:5px;" href="#editClientModal" class="edit" data-toggle="modal">
                      <i class="material-icons update" data-toggle="tooltip" data-id="<?php echo $row["id"]; ?>" data-code="<?php echo $row["code"]; ?>" data-regno="<?php echo $row["regno"]; ?>" data-vatno="<?php echo $row["vatno"]; ?>" data-name="<?php echo $row["name"]; ?>" data-address="<?php echo $row["address"]; ?>" data-phone="<?php echo $row["phone"]; ?>" data-email="<?php echo $row["email"]; ?>" data-person="<?php echo $row["person"]; ?>" title="Edit"><span class="fa fa-pencil"></span></i>
                    </a>
                    <a style="padding-left:5px;padding-right5px;" href="#deleteClientModal" class="delete" data-id="<?php echo $row["id"]; ?>" data-toggle="modal"><i class="material-icons" data-toggle="tooltip" title="Delete"><span class="fa fa-trash"></span></i></a>
                  </td>
                </tr>
              <?php
                $i++;
              }
              ?>
            </tbody>
          </table>
          <!-- Add Modal HTML -->
          <div id="addClientModal" class="modal fade">
            <div class="modal-dialog">
              <div class="modal-content">
                <form id="user_form">
                  <div class="modal-header">
                    <h4 class="modal-title">Add User</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                  </div>
                  <div class="modal-body">
                    <div class="form-group">
                      <label>CLIENT CODE</label>
                      <input type="text" id="code" name="code" class="form-control" required>
                    </div>
                    <div class="form-group">
                      <label>BUSINESS REGISTRATION NO.</label>
                      <input type="text" id="regno" name="regno" class="form-control" required>
                    </div>
                    <div class="form-group">
                      <label>VAT REGISTRAION NO.</label>
                      <input type="text" id="vatno" name="vatno" class="form-control" required>
                    </div>
                    <div class="form-group">
                      <label>NAME</label>
                      <input type="text" id="name" name="name" class="form-control" required>
                    </div>
                    <div class="form-group">
                      <label>ADDRESS</label>
                      <input type="textarear" rows="4" cols="50" id="address" name="address" class="form-control" required>
                    </div>
                    <div class="form-group">
                      <label>PHONE</label>
                      <input type="phone" id="phone" name="phone" class="form-control" required>
                    </div>
                    <div class="form-group">
                      <label>EMAIL</label>
                      <input type="email" id="email" name="email" class="form-control" required>
                    </div>
                    <div class="form-group">
                      <label>CONTACT PERSON</label>
                      <input type="text" id="person" name="person" class="form-control" required>
                    </div>
                  </div>
                  <div class="modal-footer">
                    <input type="hidden" value="1" name="type">
                    <input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel">
                    <button type="button" class="btn btn-success" id="btn-add">Add</button>
                  </div>
                </form>
              </div>
            </div>
          </div>
          <!-- Edit Modal HTML -->
          <div id="editClientModal" class="modal fade">
            <div class="modal-dialog">
              <div class="modal-content">
                <form id="update_form">
                  <div class="modal-header">
                    <h4 class="modal-title">Edit User</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                  </div>
                  <div class="modal-body">
                    <input type="hidden" id="id_u" name="id" class="form-control" required>
                    <div class="form-group">
                      <label>Code</label>
                      <input type="text" id="code_u" name="code" class="form-control" required>
                    </div>
                    <div class="form-group">
                      <label>Buiness Registration No.</label>
                      <input type="text" id="regno_u" name="regno" class="form-control" required>
                    </div>
                    <div class="form-group">
                      <label>VAT Registration No.</label>
                      <input type="text" id="vatno_u" name="vatno" class="form-control" required>
                    </div>
                    <div class="form-group">
                      <label>Name</label>
                      <input type="text" id="name_u" name="name" class="form-control" required>
                    </div>
                    <div class="form-group">
                      <label>Address</label>
                      <input type="address" id="address_u" name="address" class="form-control" required>
                    </div>
                    <div class="form-group">
                      <label>Phone No.</label>
                      <input type="phone" id="phone_u" name="phone" class="form-control" required>
                    </div>
                    <div class="form-group">
                      <label>Email</label>
                      <input type="email" id="email_u" name="email" class="form-control" required>
                    </div>
                    <div class="form-group">
                      <label>Contact Person</label>
                      <input type="text" id="person_u" name="person" class="form-control" required>
                    </div>
                  </div>
                  <div class="modal-footer">
                    <input type="hidden" value="2" name="type">
                    <input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel">
                    <button type="button" class="btn btn-info" id="update">Update</button>
                  </div>
                </form>
              </div>
            </div>
          </div>
          <!-- Delete Modal HTML -->
          <div id="deleteClientModal" class="modal fade">
            <div class="modal-dialog">
              <div class="modal-content">
                <form>
                  <div class="modal-header">
                    <h4 class="modal-title">Delete User</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                  </div>
                  <div class="modal-body">
                    <input type="hidden" id="id_d" name="idd" class="form-control">
                    <p>Are you sure you want to delete these Records?</p>
                    <p class="text-warning"><small>This action cannot be undone.</small></p>
                  </div>
                  <div class="modal-footer">
                    <input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel">
                    <button type="button" class="btn btn-danger" id="delete">Delete</button>
                  </div>
                </form>
              </div>
            </div>
          </div>
          <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script>
          <script type="text/javascript" src=" https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js"></script>
          <script type="text/javascript" src="https://cdn.datatables.net/1.10.24/js/dataTables.bootstrap5.min.js"></script>
          <style>
            .pagination {
              float: right;
              text-align: right;
            }

            .pagination .page-item.active .page-link {
              background-color: #0A2558;
            }

            div.dataTables_wrapper div.dataTables_paginate ul.pagination .page-item.active .page-link:focus {
              background-color: #0A2558;
            }

            .pagination .page-item.active .page-link:hover {
              background-color: #0A2558;
            }

            .content-table {
              border-collapse: collapse;
              margin: 5px 0;
              font-size: 0.9em;
              min-width: 400px;
              border-radius: 5px 5px 0 0;
              overflow: hidden;
              box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);
            }

            .content-table thead tr {
              background-color: #0A2558;
              color: #ffffff;
              text-align: left;
              font-weight: bold;
            }

            .content-table th,
            .content-table td {
              padding: 8px 8px;
            }

            .content-table tbody tr {
              border-bottom: 1px solid #dddddd;
            }

            .content-table tbody tr:nth-of-type(even) {
              background-color: #f3f3f3;
            }

            .content-table tbody tr:last-of-type {
              border-bottom: 2px solid #009879;
            }

            .content-table tbody tr.active-row {
              font-weight: bold;
              color: #009879;
            }

            .dataTables_filter {
              float: right;
              text-align: right;
            }
          </style>
          <script>
            $(document).ready(function() {
              $('#example').DataTable();
            });
          </script>
</body>

</html>

//MY SAVE PHP
<?php
include 'database.php';

if(count($_POST)>0){
    if($_POST['type']==1){
        $code=$_POST['code'];
        $regno=$_POST['regno'];
        $vatno=$_POST['vatno'];
        $name=$_POST['name'];
        $address=$_POST['address'];
        $phone=$_POST['phone'];
        $email=$_POST['email'];
        $person=$_POST['person'];
        
        $sql = "INSERT INTO `tbl_client`( `code`, `regno`, `vatno`, `name`, `address`, `phone`, `email`,`person`) 
        VALUES ('$code','$regno','$vatno','$name','$address','$phone','$email','$person')";
        if (mysqli_query($conn, $sql)) {
            echo json_encode(array("statusCode"=>200));
        } 
        else {
            echo "Error: " . $sql . "<br>" . mysqli_error($conn);
        }
        mysqli_close($conn);
    }
}
if(count($_POST)>0){
    if($_POST['type']==2){
        $id=$_POST['id'];
        $code=$_POST['code'];
        $regno=$_POST['regno'];
        $vatno=$_POST['vatno'];
        $name=$_POST['name'];
        $address=$_POST['address'];
        $phone=$_POST['phone'];
        $email=$_POST['email'];
        $person=$_POST['person'];

        $sql = "UPDATE `tbl_client` SET `code`='$code',`regno`='$regno',`vatno`='$vatno',`name`='$name',`address`='$address', `phone`='$phone', `email`='$email', `person`='$person' WHERE id=$id";
        if (mysqli_query($conn, $sql)) {
            echo json_encode(array("statusCode"=>200));
        } 
        else {
            echo "Error: " . $sql . "<br>" . mysqli_error($conn);
        }
        mysqli_close($conn);
    }
}
if(count($_POST)>0){
    if($_POST['type']==3){
        $idd=$_POST['id'];
        $sql = "DELETE FROM `tbl_client` WHERE id=$idd ";
        if (mysqli_query($conn, $sql)) {
            echo $idd;
        } 
        else {
            echo "Error: " . $sql . "<br>" . mysqli_error($conn);
        }
        mysqli_close($conn);
    }
}


?>
Kumar
  • 5
  • 2
  • 1
    Is this really a [mre] of the specific issue? This looks like a dump of your whole page. See also the [tour] and [ask]. We're not going to want to wade through all that until we get to the point. Basically though it sounds like you just need to issue a command to close the modal once the AJAX call has finished. – ADyson Dec 10 '21 at 11:56
  • 2
    **Warning:** Your code is vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. **Never** insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data. – ADyson Dec 10 '21 at 11:56
  • 1
    https://phpdelusions.net/mysqli also contains good examples of writing safe SQL using mysqli. See also the [mysqli documentation](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) and this: [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) . Parameterising your queries will also greatly reduce the risk of accidental syntax errors as a result of un-escaped or incorrectly quoted input values. – ADyson Dec 10 '21 at 11:56
  • @ADyson: Thank you for your comments and suggestions. The ajax code does have a modal hide but still does not seem to work on the delete row. – Kumar Dec 10 '21 at 12:17
  • 1
    I join @ADyson's comments. You should also sanitize your DB data before putting it inside the HTML. If someone enters `` in any of the fields, you may have prevented SQL injections behind but if you print it with `` then it will be executed in the browser, leading to potential XSS attacks, compromizing your app too. You should use at least `htmlentities()` or at the [`filter_*()` functions of PHP](https://www.php.net/manual/en/book.filter.php). Now, regarding your problem, it's quite some work for us to setup your app to debug it :-( – Patrick Janser Dec 10 '21 at 12:17
  • My apologies for code dumping. – Kumar Dec 10 '21 at 12:21
  • 1
    Your delete-multiple doesn't hide the modal. It's not clear which function is giving the issue. That's another reason we need a [mre] not an unfiltered code dump. Sometimes, the process of making such an example can actually reveal the problem to you as you go along, anyway. It's a good practice thing to do whenever you are stuck with debugging a problem. – ADyson Dec 10 '21 at 12:21

1 Answers1

0

Review all the bootstrap data- attributes to be sure all of them are using data-bs- prefix. I have found several in your code without it. In bootstrap 5 your bootstrap attributes should contain data-bs- instead data- to be executed correctly.

If you are migrating from bootstrap 4 check the list of migration changes here.

masterguru
  • 549
  • 4
  • 10