Delete MySQL Rows with Bootstrap Confirm Modal - onlyxcodes

Sunday 27 January 2019

Delete MySQL Rows with Bootstrap Confirm Modal

In this tutorial, I’ll explain to you how to delete MySQL rows with bootstrap confirm modal using JSP.


You know the one option already available for record deletion with confirmation which is the JavaScriot default confirm dialog, but the bootstrap confirmation dialog gives a better UI than the plain JavaScript dialog.


Before the record deleting the bootstrap confirmation modal is important because it provides the user with an opportunity to ask users to confirm whether to delete a record or not. If the users agrees then the modal will delete a record otherwise the record will be saved.


Here I used the bootbox library to build a custom bootstrap confirmation dialog and the record deletion procedure I have achieved with a fade-out effect by the jQuery Ajax method.


Delete MySQL Rows with Bootstrap Confirm Modal

Table Content

1. Database and Table Design

2. Definition: Bootbox.js

3. Include Bootstrap CSS, JS, jQuery and bootbox library

4. Fetch Record from MySQL Table

5. Confirmation Dialog Box

6. Custom Dialog Box

7. Ajax Codes to Delete Record

8. delete.jsp

9. jQuery and Ajax Complete Codes

10. Output


1. Database and Table Design

First, you need to create a database under your PHPMyAdmin with any name after that copy and paste the below SQL code into your database to create a table.


I used bootstrap_modal_confirm_delete_db named database and established a table called mobile.


CREATE TABLE `tbl_mobile` (
  `id` int(11) NOT NULL,
  `mobile_name` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT;

create mobile table in the database

I have inserted four dumping records in the table.


INSERT INTO `tbl_mobile` (`id`, `mobile_name`) VALUES
(1, 'Apple iPhone X'),
(2, 'mi note 4'),
(3, 'OPPO F9'),
(4, 'VIVO V11');  

inserted dumping record in the table

2. Definition : Bootbox.js

Bootbox.js is a small JavaScript library which allows you to create programmatic dialog boxes using Bootstrap modals, without having to worry about creating, managing or removing any of the required DOM elements or JS event handlers. Here’s the simplest possible example: ( according to bootbox official site )


3. Include Bootstrap CSS, JS, jQuery and bootbox library

Bootstrap – In this project, you are required to include the bootstrap package.


I have created theindex.jsp file.


I have included all library files jQuery, bootstrap, and boot box alert library.


<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<script src="js/jquery-1.12.4-jquery.min.js" type="text/javascript"></script>
<script src="bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<script src="js/bootbox.min.js" type="text/javascript"></script> 

4. Fetch Record from MySQL Table

The below code retrieves mobile records from the table and I have set up it in tabular format.


Look at the last anchor tag which is used to delete the record along with the table ID.


<td><a data_mobile_id="<%=rs.getInt("id")%>" href="javascript:void(0)" class="btn btn-sm btn-danger"><i class="glyphicon glyphicon-trash"></i></a></td> 

The attribute data_mobile_id collected the table id and that will activate the btn-danger class attribute using the jQuery click case and delete a specific record from the table.


See the full code for retrieving records from the table that I have set in table format.


 <table class="table table-striped table-bordered table-hover">
    <thead>
        <tr>
            <th>Mobile Name</th>
            <th>Delete</th>
        </tr>
    </thead>
    <%
        String dburl="jdbc:mysql://localhost:3306/bootstrap_modal_confirm_delete_db";         String dbusername="root"; //database username   
        String dbpassword =""; //database password
                                
        try
        {
            Class.forName("com.mysql.jdbc.Driver"); //load driver
            Connection con=DriverManager.getConnection(dburl,dbusername,dbpassword); //create connection
                                    
            PreparedStatement pstmt=null; //create statement 
                                    
            pstmt=con.prepareStatement("SELECT * FROM tbl_mobile"); //sql select query
            ResultSet rs=pstmt.executeQuery();
                                    
            while(rs.next())
            {
           %>
            <tbody>
                <tr>
                    <td><%=rs.getString("mobile_name")%></td>
                    <td><a data_mobile_id="<%=rs.getInt("id")%>" href="javascript:void(0)" class="btn btn-sm btn-danger"><i class="glyphicon glyphicon-trash"></i></a></td>
                </tr>
            </tbody>
            <%
            }
        }
        catch(Exception e)
        {
           e.printStackTrace();
        }
    %>
</table>

5. Confirmation Dialog Box

See the confirmation dialog below for the popup ordered from the JavaScript library bootbox. 


bootbox.confirm('Are you sure ?',function(response){
 //delete code beginning here 
}); 

6. Custom Dialog Box

See the custom dialog box below I outlined how it works to delete records.


$('.btn-danger').click() – Get attribute anchor tag class name btn-danger for click event success. 


var id = $(this).attr('data_mobile_id') – Get current mobile Id and return current table Id with attr() method. The current id hold by id variable. 


var parent = $(this).parent('td').parent('tr'); – This will cause a slow fade-out effect on the < tr > tag row when the record is deleted. 


Next, you can see the custom dialog and two callback functions.


In the first function, if you click the No button, then the modal will hide your data and save it.


In the second function, I have built ajax() method for deleting records.


$(document).ready(function(){
    $('.btn-danger').click(function(e){
       e.preventDefault();
       var id = $(this).attr('data_mobile_id');
       var parent = $(this).parent('td').parent('tr');
       bootbox.dialog({
           message: 'My Custom Dialogue',
           title: "<i class='glyphicon glyphicon-trash'></i> Delete !",
           buttons:{
               success:{
                   label: 'No',
                   className: 'btn-success',
                   callback: function(){
                       //cancel button, close dialogue box 
               },
               danger:{
                   label: 'Delete!',
                   className: 'btn-danger',
                   callback: function(){
                       
                     //ajax delete code beginning here
                   }
               }   
           }
       });
    });      
}); 

7. Ajax Codes to Delete Record

Underneath the second callback function, I have set up the ajax() full code.


$.ajax({
    type: 'POST',
    url: 'delete.jsp',
    data: 'delete_id='+id
    })
    .done(function(data){
        bootbox.alert(data);
        parent.fadeOut('slow');   
    })
    .fail(function(){
        bootbox.alert('Error...');
    }); 

8. delete.jsp

This file will communicate peacefully from the ajax() function and after obtaining the correct clicked row ID, this will delete the row and screen the data deletion message being a result in the alert box.


<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%
    if(request.getParameter("delete_id")!=null) 
    {
        int id=Integer.parseInt(request.getParameter("delete_id")); 
      
        String dburl="jdbc:mysql://localhost:3306/bootstrap_modal_confirm_delete_db"; 
        String dbusername="root"; //database username   
        String dbpassword =""; //database password
        
        try
        {
            Class.forName("com.mysql.jdbc.Driver"); //load driver
            Connection con=DriverManager.getConnection(dburl,dbusername,dbpassword); //create connection
                                    
            PreparedStatement pstmt=null; //create statement
            
            pstmt=con.prepareStatement("DELETE FROM tbl_mobile WHERE id=?"); 
            pstmt.setInt(1,id); 
            pstmt.executeUpdate(); //execute query
            
            out.print("Data Deleted Successfully...."); 
            
            pstmt.close(); //close statement
            con.close(); //close connection
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
%> 

9. jQuery Ajax Complete Codes

See below complete jQuery Ajax codes to activate the bootstrap confirmation dialog that I have discussed separately above.


<script type="text/javascript">
$(document).ready(function(){
    $('.btn-danger').click(function(e){
       e.preventDefault();
       var id = $(this).attr('data_mobile_id');
       var parent = $(this).parent('td').parent('tr');
       bootbox.dialog({
           message: 'Are you sure you want to Delete ?',
           title: "<i class='glyphicon glyphicon-trash'></i> Delete !",
           buttons:{
               success:{
                   label: 'No',
                   className: 'btn-success',
                   callback: function(){
                       $('.bootbox').modal('hide');
                   }
               },
               danger:{
                   label: 'Delete!',
                   className: 'btn-danger',
                   callback: function(){
                       $.ajax({
                          type: 'POST',
                          url: 'delete.jsp',
                          data: 'delete_id='+id
                       })
                        .done(function(data){
                            bootbox.alert(data);
                            parent.fadeOut('slow');   
                       })
                       .fail(function(){
                           bootbox.alert('Error...');
                       });
                   }
               }   
           }
       });
    });      
});
</script> 
 

10. Output: Confirmation Dialog

bootstrap confirmation dialog - delete mysql rows with bootstrap confirm modal

Record Deletion Alert Dialog

record deletion alert dialog - delete mysql rows with bootstrap confirm modal

Download Codes

No comments:

Post a Comment

Post Bottom Ad