Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Wednesday, April 26, 2023

Ajax CRUD Operation in CodeIgniter with Example

 

CRUD (Create, Read, Update, Delete) is a common part of any dynamic web application. We generally add new records into database or display records from database and then perform further operations like update, delete on same records.

So if you’re developing web applications using CodeIgniter then you have certainly handled CRUD operations in your application. But its not very user friendly if you have handled this with pure CodeIgniter because it loads page every time when you perform actions.

So here in this tutorial, we have handled CRUD operations using Ajax with CodeIgniter. You would also like to checkout tutorial about Multiple Image Upload in CodeIgniter with example.

We will cover this tutorial in easy steps with live example with ajax CRUD operations in CodeIgniter. So let’s start.

 

Before going through CRUD functionality, we hope that you have setup your CodeIgniter application with database connection details to use with this example. So let’s start.

Step1: Create MySQL Database Table

As we will cover CRUD operations tutorial with live example , so first we will create MySQL database table emp using below table create query.

CREATE TABLE `emp` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `skills` varchar(255) NOT NULL,
  `address` varchar(255) NOT NULL,
  `designation` varchar(255) NOT NULL,
  `age` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Step2: Create Model for Employee Data

We will create model file empModel.php in application/models directory and define method to get employee list, save, update and delete employee records.

<?php
class EmpModel extends CI_Model{
	function employeeList(){
		$hasil=$this->db->get('emp');
		return $hasil->result();
	}
	function saveEmp(){
		$data = array(				
				'name' 			=> $this->input->post('name'), 
				'age' 			=> $this->input->post('age'), 
				'designation' 	=> $this->input->post('designation'), 
				'skills' 		=> $this->input->post('skills'), 
				'address' 		=> $this->input->post('address'), 
			);
		$result=$this->db->insert('emp',$data);
		return $result;
	}
	function updateEmp(){
		$id=$this->input->post('id');
		$name=$this->input->post('name');
		$age=$this->input->post('age');
		$designation=$this->input->post('designation');
		$skills=$this->input->post('skills');
		$address=$this->input->post('address');
		$this->db->set('name', $name);
		$this->db->set('age', $age);
		$this->db->set('designation', $designation);
		$this->db->set('skills', $skills);
		$this->db->set('address', $address);
		$this->db->where('id', $id);
		$result=$this->db->update('emp');
		return $result;	
	}
	function deleteEmp(){
		$id=$this->input->post('id');
		$this->db->where('id', $id);
		$result=$this->db->delete('emp');
		return $result;
	}	
}

Step3: Create Emp Controllers

Now we will create controllers file Emp.php in application/controllers directory to load Model and Model method.

<?php
class Emp extends CI_Controller{
	function __construct(){
		parent::__construct();
		$this->load->model('EmpModel');
	}
	function index(){
		$this->load->view('listEmp');
	}
	function show(){
		$data=$this->EmpModel->employeeList();
		echo json_encode($data);
	}
	function save(){
		$data=$this->EmpModel->saveEmp();
		echo json_encode($data);
	}
	function update(){
		$data=$this->EmpModel->updateEmp();
		echo json_encode($data);
	}
	function delete(){
		$data=$this->EmpModel->deleteEmp();
		echo json_encode($data);
	}
}

Step4: Create View for Employee Listing

We will create views listEmp.php in application/views directory to load employee list. We will create jQuery Datatables to load employee records with Ajax request data in listRecords Datatable container..

 <table class="table table-striped" id="employeeListing">
	<thead>
		<tr>
			<th>Name</th>
			<th>Age</th>
			<th>Skills</th>
			<th>Desgination</th>
			<th>Address</th>
			<th style="text-align: right;">Actions</th>
		</tr>
	</thead>
	<tbody id="listRecords">                    
	</tbody>
</table>

Step5: Load Employee Data with Ajax

We will create JavaScript file crud_operation.js and create function listEmployee() and make Ajax request to emp/show controllers to get employee data from database and set in Datatables.

function listEmployee(){
	$.ajax({
		type  : 'ajax',
		url   : 'emp/show',
		async : false,
		dataType : 'json',
		success : function(data){
			var html = '';
			var i;
			for(i=0; i<data.length; i++){
				html += '<tr id="'+data[i].id+'">'+
						'<td>'+data[i].name+'</td>'+
						'<td>'+data[i].age+'</td>'+
						'<td>'+data[i].skills+'</td>'+		                        
						'<td>'+data[i].designation+'</td>'+
						'<td>'+data[i].address+'</td>'+
						'<td style="text-align:right;">'+
							'<a href="javascript:void(0);" class="btn btn-info btn-sm editRecord" data-id="'+data[i].id+'" data-name="'+data[i].name+'" data-age="'+data[i].age+'" data-skills="'+data[i].skills+'" data-designation="'+data[i].designation+'" data-address="'+data[i].address+'">Edit</a>'+' '+
							'<a href="javascript:void(0);" class="btn btn-danger btn-sm deleteRecord" data-id="'+data[i].id+'">Delete</a>'+
						'</td>'+
						'</tr>';
			}
			$('#listRecords').html(html);					
		}
	});
}

Step6: Create Add Employee Form

We will create add new employee Form HTML in views listEmp.php in application/views directory to add new employee record.

<form id="saveEmpForm" method="post">
	<div class="modal fade" id="addEmpModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
	  <div class="modal-dialog modal-lg" role="document">
		<div class="modal-content">
		  <div class="modal-header">
			<h5 class="modal-title" id="exampleModalLabel">Add New Employee</h5>
			<button type="button" class="close" data-dismiss="modal" aria-label="Close">
			  <span aria-hidden="true">×</span>
			</button>
		  </div>
		  <div class="modal-body">                       
				<div class="form-group row">
					<label class="col-md-2 col-form-label">Name*</label>
					<div class="col-md-10">
					  <input type="text" name="name" id="name" class="form-control" required>
					</div>
				</div>
				<div class="form-group row">
					<label class="col-md-2 col-form-label">Age*</label>
					<div class="col-md-10">
					  <input type="text" name="age" id="age" class="form-control" required> 
					</div>
				</div>
				<div class="form-group row">
					<label class="col-md-2 col-form-label">Skills*</label>
					<div class="col-md-10">
					  <input type="text" name="skills" id="skills" class="form-control" required>
					</div>
				</div>
				<div class="form-group row">
					<label class="col-md-2 col-form-label">Designation*</label>
					<div class="col-md-10">
					  <input type="text" name="designation" id="designation" class="form-control" required>
					</div>
				</div>
				<div class="form-group row">
					<label class="col-md-2 col-form-label">Address*</label>
					<div class="col-md-10">
					  <textarea name="address" id="address" class="form-control" rows="5" required></textarea>
					</div>
				</div>
		  </div>
		  <div class="modal-footer">
			<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
			<button type="submit" class="btn btn-primary">Save</button>
		  </div>
		</div>
	  </div>
	</div>
</form>

Step7: Save Emploee with Ajax

In JavaScript file crud_operation.js, we will handle functionality to save new employee record using Ajax to make request to emp/save controllers.

$('#saveEmpForm').submit('click',function(){
		var empName = $('#name').val();
		var empAge = $('#age').val();
		var empDesignation = $('#designation').val();
		var empSkills = $('#skills').val();
		var empAddress = $('#address').val();
		$.ajax({
			type : "POST",
			url  : "emp/save",
			dataType : "JSON",
			data : {name:empName, age:empAge, designation:empDesignation, skills:empSkills, address:empAddress},
			success: function(data){
				$('#name').val("");
				$('#skills').val("");
				$('#address').val("");
				$('#addEmpModal').modal('hide');
				listEmployee();
			}
		});
		return false;
	});

Step8: Create Edit Employee Form

We will create edit employee Form HTML in views listEmp.php in application/views directory to edit employee record.

<form id="editEmpForm" method="post">
	<div class="modal fade" id="editEmpModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
	  <div class="modal-dialog modal-lg" role="document">
		<div class="modal-content">
		  <div class="modal-header">
			<h5 class="modal-title" id="editModalLabel">Edit Employee</h5>
			<button type="button" class="close" data-dismiss="modal" aria-label="Close">
			  <span aria-hidden="true">×</span>
			</button>
		  </div>
		  <div class="modal-body">
				<div class="form-group row">
					<label class="col-md-2 col-form-label">Name*</label>
					<div class="col-md-10">
					  <input type="text" name="empName" id="empName" class="form-control" placeholder="Name" required>
					</div>
				</div>
				<div class="form-group row">
					<label class="col-md-2 col-form-label">Age*</label>
					<div class="col-md-10">
					  <input type="text" name="empAge" id="empAge" class="form-control" placeholder="Age" required>
					</div>
				</div>				
				<div class="form-group row">
					<label class="col-md-2 col-form-label">Skills*</label>
					<div class="col-md-10">
					  <input type="text" name="empSkills" id="empSkills" class="form-control" placeholder="Skils" required>
					</div>
				</div>
				<div class="form-group row">
					<label class="col-md-2 col-form-label">Designation*</label>
					<div class="col-md-10">
					  <input type="text" name="empDesignation" id="empDesignation" class="form-control" placeholder="Skils" required>
					</div>
				</div>
				<div class="form-group row">
					<label class="col-md-2 col-form-label">Address*</label>
					<div class="col-md-10">
					   <textarea name="empAddress" id="empAddress" class="form-control" rows="5" required></textarea>
					</div>
				</div>
		  </div>
		  <div class="modal-footer">
			 <input type="hidden" name="empId" id="empId" class="form-control">
			<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
			<button type="submit" class="btn btn-primary">Update</button>
		  </div>
		</div>
	  </div>
	</div>
</form>

Step9: Edit Save Employee with Ajax

In JavaScript file crud_operation.js, we will handle functionality to edit save employee record using Ajax to make request to emp/update controllers.

$('#editEmpForm').on('submit',function(){
		var empId = $('#empId').val();
		var empName = $('#empName').val();
		var empAge = $('#empAge').val();
		var empDesignation = $('#empDesignation').val();
		var empSkills = $('#empSkills').val();
		var empAddress = $('#empAddress').val();			
		$.ajax({
			type : "POST",
			url  : "emp/update",
			dataType : "JSON",
			data : {id:empId, name:empName, age:empAge, designation:empDesignation, skills:empSkills, address:empAddress},
			success: function(data){
				$("#empId").val("");
				$("#empName").val("");
				$('#empAge').val("");
				$("#empSkills").val("");
				$('#empDesignation').val("");
				$("#empAddress").val("");
				$('#editEmpModal').modal('hide');
				listEmployee();
			}
		});
		return false;
	});

Step10: Create Delete Employee Form

We will create delete employee Form HTML in views listEmp.php in application/views directory to delete employee record.

<form id="deleteEmpForm" method="post">
	<div class="modal fade" id="deleteEmpModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
	  <div class="modal-dialog" role="document">
		<div class="modal-content">
		  <div class="modal-header">
			<h5 class="modal-title" id="deleteModalLabel">Delete Employee</h5>
			<button type="button" class="close" data-dismiss="modal" aria-label="Close">
			  <span aria-hidden="true">×</span>
			</button>
		  </div>
		  <div class="modal-body">
			   <strong>Are you sure to delete this record?</strong>
		  </div>
		  <div class="modal-footer">
			<input type="hidden" name="deleteEmpId" id="deleteEmpId" class="form-control">
			<button type="button" class="btn btn-secondary" data-dismiss="modal">No</button>
			<button type="submit" class="btn btn-primary">Yes</button>
		  </div>
		</div>
	  </div>
	</div>
</form>

Step11: Delete Employee with Ajax

In JavaScript file crud_operation.js, we will handle functionality to delete employee record using Ajax to make request to emp/delete controllers.

 $('#deleteEmpForm').on('submit',function(){
		var empId = $('#deleteEmpId').val();
		$.ajax({
			type : "POST",
			url  : "emp/delete",
			dataType : "JSON",  
			data : {id:empId},
			success: function(data){
				$("#"+empId).remove();
				$('#deleteEmpId').val("");
				$('#deleteEmpModal').modal('hide');
				listEmployee();
			}
		});
		return false;
	});

 

No comments:

Post a Comment