Update and delete rows from database with bootstrap confirm modal in Codeigniter

In this tutorial, you will learn how to implement records Update and delete with Bootstrap confirm modal using codeigniter. When perform alter operation on database we need to make sure to delete the records or not. JavaScript provide default confirms modal but Bootstrap confirms dialogs are very smooth and better UI than default JavaScript confirm dialog.So here we have covered up functionality to display records with PHP and MySQL and then handle record delete and update with Bootstrap Confirm Modal using Bootstrap Modal plugin.

Create database tables:

CREATE TABLE `tbl_data` (
  `id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `address` varchar(200) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Database Configuration (Application/config/database.php)

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'ci_ajax_db',
	'dbdriver' => 'mysqli',
	'dbprefix' => '',
	'pconnect' => FALSE,
	'db_debug' => (ENVIRONMENT !== 'production'),
	'cache_on' => FALSE,
	'cachedir' => '',
	'char_set' => 'utf8',
	'dbcollat' => 'utf8_general_ci',
	'swap_pre' => '',
	'encrypt' => FALSE,
	'compress' => FALSE,
	'stricton' => FALSE,
	'failover' => array(),
	'save_queries' => TRUE
);

Controllers (Application/controllers/Main_controller.php)

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Main_controller extends CI_Controller {

	function __construct()
	{
		parent:: __construct();
	}


	public function index()
	{
		$this->load->view('layout/header');
		$this->load->view('blog/index');
		$this->load->view('layout/footer');
	}

	public function showallData()
	{
		# code...
		$result= $this->Data_m->showallData();
		echo json_encode($result);

	}

	public function addData()
	{
		# code...
		$result= $this->Data_m->addData();

		$msg['type']='add';

		$msg['success'] =false;
		if ($result) {
			# code...
			$msg['success'] =true;
		}

		echo json_encode($msg);
	}

	public function editData()
	{
		$result= $this->Data_m->editData();
		echo json_encode($result);
		# code...
	}

	public function updateData()
	{
		# code...
		$result= $this->Data_m->updateData();
		$msg['type']='update';
		$msg['success'] =false;
		if ($result) {
			# code...
			$msg['success'] =true;
		}
		echo json_encode($msg);
	}

	public function deleteData()
	{
		# code...
		$result= $this->Data_m->deleteData();
		$msg['type']='delete';
		$msg['success'] =false;
		if ($result) {
			# code...
			$msg['success'] =true;
		}
		echo json_encode($msg);
	}

}

View (Application/views/layout/Com_box.php)

<div class="container">

<div style="padding: 10px; margin-top: 12px;">
<center>	<h3>
		 CRUD with Codeigniter, Jquery and ajax
	</h3></center>
	<div class="alert alert-success" id="alerti" style="display: none;">
		
	</div>

	<button id="btnAdd" class="btn btn-success" style="margin-bottom: 10px;">Add new</button>
	 <table  class="table table-bordered" >
	 	<thead>
	 		<tr>
	 			<td>ID</td>
	 			<td>Name</td>
	 			<td>Address</td>
	 			<td>Edit</td>
	 			<td>Delete</td>
	 		</tr>
	 	</thead>

	 		<tbody id="showdata">
	 			
	 		</tbody>
	 </table>
</div>
</div>

<div id="myModal" class="modal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <form id="myform" action="" method="post" class="form-horizontal"> 
        	<input type="hidden" name="txtID" value="0"> 	
        	<div class="form-group">
        		<label for="name" class="label-control">Eployee Name</label>
        		<input type="text" name="textName" class="form-control" required>
        	</div>
        	<div class="form-group">
        		<label for="address" class="label-control">Eployee address</label>
        		<textarea class="form-control" name="address" required></textarea>
        	</div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button id="btnSave" type="button" class="btn btn-primary">Save changes</button>
      </div> 	
    </div>
  </div>
</div>

<div id="myModalDelete" class="modal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
      	You want to delete this record ?
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button id="btdelete" type="button" class="btn btn-danger">DELETE</button>
      </div> 	
    </div>
  </div>
</div>

Javascript

$(function(){	
showallData();
//Add new
$('#btnAdd').click(function(){
	$('#myform')[0].reset();
	$('#myModal').modal('show');
	$('#myModal').find('.modal-title').text('Add new Data.');
	$('#myform').attr('action','<?php echo base_url(); ?>Main_controller/addData');
});
//for save / insert data

$('#btnSave').click(function(){
	var url = $('#myform').attr('action');
	var data = $('#myform').serialize();
	// validation 
	var name = $('input[name=textName]');
	var address = $('textarea[name=address]');
	// var result = '';

if (name.val()=='') {

	alert('Please Enter name');
}

else if (address.val()=='') {

	alert('Please Enter address');

}

else{
	
	$.ajax({
		type: 'ajax',
		method:'post',
		url: url,
		data: data,
		async: false,
		dataType: 'json',
		success: function(response){
				$('#myform')[0].reset();
				$('#myModal').modal('hide');
				if (response.type=='add') {	
					var types='added';
				}
				else if (response.type=='update') {
					var types='updated';
				}

				$('#alerti').html('Data successfully '+types+'.').fadeIn().delay(4000).fadeOut('slow');
				showallData();
		},
		error: function(){
			alert('Data not inserted.');
		}
	});


}

});


//edit
$('#showdata').on('click', '.item-edit', function(){
	var id = $(this).attr('data');
	$('#myModal').modal('show');
	$('#myModal').find('.modal-title').text('Edit Data');
	$('#myform').attr('action','<?php echo base_url(); ?>Main_controller/updateData')
	$.ajax({
		type: 'ajax',
		method: 'get',
		url: '<?php echo base_url(); ?>Main_controller/editData',
		data:{id: id},	
		async: false,
		dataType: 'json',
		success: function(data){
			$('input[name=textName]').val(data.name);
			$('textarea[name=address]').val(data.address);
			$('input[name=txtID]').val(data.id);
		},
		error: function(){
			alert('could not Edit data');
		}
	});

});


//data deleting
$('#showdata').on('click','.item-delete',function(){
	var id= $(this).attr('data');
	$('#myModalDelete').modal('show');
	$('#btdelete').unbind().click(function(){
		$.ajax({
			type: 'ajax',
			method: 'get',
			async: false,
			url: '<?php echo base_url(); ?>Main_controller/deleteData',
			data: {id: id},
			dataType: 'json',
			success: function(response)
			{

				$('#myModalDelete').modal('hide');
				$('#alerti').html('Data successfully Deleted.').fadeIn().delay(4000).fadeOut('slow');
				showallData();
			},

			error: function()
			{
				alert('Error in deleting');
			}
		});

	});

});



//function
		function showallData(){
			$.ajax({
				type: 'ajax',
				url: '<?php echo base_url() ?>Main_controller/showAllData',
				async: false,
				dataType: 'json',
				success: function(data) {
					// body...

					var html ='';
					var i;
						for (i =0 ; i<data.length; i++) {
						
						html+=	'<tr>'+
					 				'<td>'+data[i].id+'</td>'+
					 				'<td>'+data[i].name+'</td>'+
					 				'<td>'+data[i].address+'</td>'+
					 				
				 				'<td>'+
				 					'<a href="javascript:;" class="btn btn-info item-edit" data="'+data[i].id+'">Edit</a>'+
				 					
				 				'</td>'+
				 				'<td>'+'<a href="javascript:;" class="btn btn-danger item-delete" data="'+data[i].id+'">Delete</a>'+
				 				'</td>'+
				 			'</tr>';
						}

						$('#showdata').html(html);	
					},
					error: function()
					{
						alert('Data not Found.');

					}

			});
		}
	});