Codeigniter 4 CRUD Operation With Ajax Example – onlinecode

Codeigniter 4 CRUD Operation With Ajax Example – onlinecode

In this post we will give you information about Codeigniter 4 CRUD Operation With Ajax Example – onlinecode. Hear we will give you detail about Codeigniter 4 CRUD Operation With Ajax Example – onlinecodeAnd how to use it also give you demo for it if it is necessary.

In this article, We will inform you how to perform crud operation with ajax in CodeIgniter 4.CRUD stands for create, read, update, and delete. if you create a user-friendly website at that time need to crud operation.

if you want to create CRUD operation with ajax in CodeIgniter 4, then the first configuration of the database and connect the MySQL database then after creating CRUD operation with ajax in Codeigniter 4.

in our post through, We will go how to connect CodeIgniter 4 to MySQL and perform the CRUD operation.

if you want to create CRUD operation in CodeIgniter 4, so you can follow the below steps.OverviewStep 1: Download CodeigniterStep 2: Basic ConfigurationsStep 3: Create a Database in tableStep 4: Connect to DatabaseStep 5: Create Controller and ModelStep 6: Create Views FilesStep 7: Run The Application

Step 1: Download CodeigniterIf you want to download or install CodeIgniter 4 then you can below Url.How To Install Codeigniter 4 Using Manual, Composer, Git

Step 2: Basic ConfigurationsIf you want to Basic Configurations in your project then you can below Url.Codeigniter 4 Removing Index.Php From Url

Step 3: Create a Database in tableIn this step, We will create the database and table.

CREATE TABLE IF NOT EXISTS 'students' (
  'id' int(11) NOT NULL AUTO_INCREMENT,
  'first_name' varchar(64) NOT NULL,
  'last_name' varchar(64) NOT NULL,
  'address' text NOT NULL,
  PRIMARY KEY ('id')
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ;

Step 4: Connect to DatabaseGo to the “app/Config/Database.php” folder and open database.php file some changes in this file like hostname, database username, database password, and database name.

	public $default = [
		'DSN'      => '',
		'hostname' => 'localhost',
		'username' => 'root',
		'password' => '',
		'database' => 'codeigniter4_crud',
		'DBDriver' => 'MySQLi',
		'DBPrefix' => '',
		'pConnect' => false,
		'DBDebug'  => (ENVIRONMENT !== 'production'),
		'cacheOn'  => false,
		'cacheDir' => '',
		'charset'  => 'utf8',
		'DBCollat' => 'utf8_general_ci',
		'swapPre'  => '',
		'encrypt'  => false,
		'compress' => false,
		'strictOn' => false,
		'failover' => [],
		'port'     => 3306,
	];

Step 5: Create Controller and ModelIn this step, we will a create “Student.php” controller and “StudentModel.php” model.app/Controllers/Student.php

<?php namespace AppControllers;
 
use CodeIgniterController;
use AppModelsStudentModel;
 
class Student extends Controller
{
 
    public function index()
    {    
        $model = new StudentModel();
 
        $data['students_detail'] = $model->orderBy('id', 'DESC')->findAll();
        
        return view('list', $data);
    }    

 
    public function store()
    {  
        helper(['form', 'url']);
         
        $model = new StudentModel();
		
        $data = [
            'first_name' => $this->request->getVar('txtFirstName'),
            'last_name'  => $this->request->getVar('txtLastName'),
            'address'  => $this->request->getVar('txtAddress'),
            ];
        $save = $model->insert_data($data);
		if($save != false)
		{
			$data = $model->where('id', $save)->first();
			echo json_encode(array("status" => true , 'data' => $data));
		}
		else{
			echo json_encode(array("status" => false , 'data' => $data));
		}
    }
 
    public function edit($id = null)
    {
      
     $model = new StudentModel();
	
     $data = $model->where('id', $id)->first();
	 
    if($data){
			echo json_encode(array("status" => true , 'data' => $data));
		}else{
			echo json_encode(array("status" => false));
		}
    }
 
    public function update()
    {  
 
		helper(['form', 'url']);
		 
		$model = new StudentModel();

		$id = $this->request->getVar('hdnStudentId');

		 $data = [
			'first_name' => $this->request->getVar('txtFirstName'),
			'last_name'  => $this->request->getVar('txtLastName'),
			'address'  => $this->request->getVar('txtAddress'),
			];

		$update = $model->update($id,$data);
		if($update != false)
		{
			$data = $model->where('id', $id)->first();
			echo json_encode(array("status" => true , 'data' => $data));
		}
		else{
			echo json_encode(array("status" => false , 'data' => $data));
		}
    }
 
    public function delete($id = null){
		$model = new StudentModel();
		$delete = $model->where('id', $id)->delete();
		if($delete)
		{
		   echo json_encode(array("status" => true));
		}else{
		   echo json_encode(array("status" => false));
		}
    }
}

?>

app/Models/StudentModel.php

<?php namespace AppModels;
use CodeIgniterDatabaseConnectionInterface;
use CodeIgniterModel;
 
class StudentModel extends Model
{
    protected $table = 'Students';
 
    protected $allowedFields = ['first_name','last_name','address'];
	
	public function __construct() {
        parent::__construct();
        //$this->load->database();
        $db = ConfigDatabase::connect();
        $builder = $db->table('Students');
    }
	
	public function insert_data($data) {
		if($this->db->table($this->table)->insert($data))
        {
            return $this->db->insertID();
        }
        else
        {
            return false;
        }
    }
}
?>

Step 6: Create Views FilesFinally, we will create the list.php, add.php, and edit.php in the app/views directory.app/views/list.php

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Codeigniter 4 CRUD Operation With Ajax Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
</head>
<body>
<div >
    <div >
        <div >
            <h2>Codeigniter 4 Ajax CRUD Example</h2>
        </div>
        <div >
            <a  href="#" data-toggle="modal" data-target="#addModal">Add</a>
        </div>
    </div>

    <table  id="studentTable">
		<thead>
			<tr>
				<th>id</th>
				<th>First Name</th>
				<th>Last Name</th>
				<th>Address</th>
				<th width="280px">Action</th>
			</tr>
		</thead>	
		<tbody>
       <?php
		foreach($students_detail as $row){
		?>
		<tr id="<?php echo $row['id']; ?>">
			<td><?php echo $row['id']; ?></td>
			<td><?php echo $row['first_name']; ?></td>
			<td><?php echo $row['last_name']; ?></td>
			<td><?php echo $row['address']; ?></td>
			<td>
			<a data-id="<?php echo $row['id']; ?>" >Edit</a>
			<a data-id="<?php echo $row['id']; ?>" >Delete</a>
			</td>
		</tr>
	<?php
}
?>
	</tbody>
</table>
		<!-- Add Student Modal -->
		<div id="addModal"  role="dialog">
		  <div >
		 
			<!-- User Student content-->
			<div >
			  <div >
				<button type="button"  data-dismiss="modal">&times;</button>
				<h4 >Add New Student</h4>
			  </div>
			  <div >
				<form id="addStudent" name="addStudent" action="<?php echo site_url('student/store');?>" method="post">
					<div >
						<label for="txtFirstName">First Name:</label>
						<input type="text"  id="txtFirstName" placeholder="Enter First Name" name="txtFirstName">
					</div>
					<div >
						<label for="txtLastName">Last Name:</label>
						<input type="text"  id="txtLastName" placeholder="Enter Last Name" name="txtLastName">
					</div>
					<div >
						<label for="txtAddress">Address:</label>
						<pre  id="txtAddress" name="txtAddress" rows="10" placeholder="Enter Address"></pre>
					</div>
					<button type="submit" >Submit</button>
				</form>
			  </div>
			  <div >
				<button type="button"  data-dismiss="modal">Close</button>
			  </div>
			</div>
		  </div>
		</div>	
		<!-- Update User Modal -->
		<div id="updateModal"  role="dialog">
		  <div >
		 
			<!-- User Modal content-->
			<div >
			  <div >
				<button type="button"  data-dismiss="modal">&times;</button>
				<h4 >Update Student</h4>
			  </div>
			  <div >
				<form id="updateStudent" name="updateStudent" action="<?php echo site_url('student/update');?>" method="post">
					<input type="hidden" name="hdnStudentId" id="hdnStudentId"/>
					<div >
						<label for="txtFirstName">First Name:</label>
						<input type="text"  id="txtFirstName" placeholder="Enter First Name" name="txtFirstName">
					</div>
					<div >
						<label for="txtLastName">Last Name:</label>
						<input type="text"  id="txtLastName" placeholder="Enter Last Name" name="txtLastName">
					</div>
					<div >
						<label for="txtAddress">Address:</label>
						<pre  id="txtAddress" name="txtAddress" rows="10" placeholder="Enter Address"></pre>
					</div>
					<button type="submit" >Submit</button>
				</form>
			  </div>
			  <div >
				<button type="button"  data-dismiss="modal">Close</button>
			  </div>
			</div>
		  </div>
		</div>	 
		<script>
		  $(document).ready(function () {
			//Add the Student  
			$("#addStudent").validate({
				 rules: {
						txtFirstName: "required",
						txtLastName: "required",
						txtAddress: "required"
					},
					messages: {
					},
		 
				 submitHandler: function(form) {
				  var form_action = $("#addStudent").attr("action");
				  $.ajax({
					  data: $('#addStudent').serialize(),
					  url: form_action,
					  type: "POST",
					  dataType: 'json',
					  success: function (res) {
						  var student = '<tr id="'+res.data.id+'">';
						  student += '<td>' + res.data.id + '</td>';
						  student += '<td>' + res.data.first_name + '</td>';
						  student += '<td>' + res.data.last_name + '</td>';
						  student += '<td>' + res.data.address + '</td>';
						  student += '<td><a data-id="' + res.data.id + '" >Edit</a>&nbsp;&nbsp;<a data-id="' + res.data.id + '" >Delete</a></td>';
						  student += '</tr>';            
						  $('#studentTable tbody').prepend(student);
						  $('#addStudent')[0].reset();
						  $('#addModal').modal('hide');
					  },
					  error: function (data) {
					  }
				  });
				}
			});
		  
		 
			//When click edit Student
			$('body').on('click', '.btnEdit', function () {
			  var student_id = $(this).attr('data-id');
			   $.ajax({
					  url: 'student/edit/'+student_id,
					  type: "GET",
					  dataType: 'json',
					  success: function (res) {
						  $('#updateModal').modal('show');
						  $('#updateStudent #hdnStudentId').val(res.data.id); 
						  $('#updateStudent #txtFirstName').val(res.data.first_name);
						  $('#updateStudent #txtLastName').val(res.data.last_name);
						  $('#updateStudent #txtAddress').val(res.data.address);
					  },
					  error: function (data) {
					  }
				});
		   });
			// Update the Student
			$("#updateStudent").validate({
				 rules: {
						txtFirstName: "required",
						txtLastName: "required",
						txtAddress: "required"
					},
					messages: {
					},
				 submitHandler: function(form) {
				  var form_action = $("#updateStudent").attr("action");
				  $.ajax({
					  data: $('#updateStudent').serialize(),
					  url: form_action,
					  type: "POST",
					  dataType: 'json',
					  success: function (res) {
						  var student = '<td>' + res.data.id + '</td>';
						  student += '<td>' + res.data.first_name + '</td>';
						  student += '<td>' + res.data.last_name + '</td>';
						  student += '<td>' + res.data.address + '</td>';
						  student += '<td><a data-id="' + res.data.id + '" >Edit</a>&nbsp;&nbsp;<a data-id="' + res.data.id + '" >Delete</a></td>';
						  $('#studentTable tbody #'+ res.data.id).html(student);
						  $('#updateStudent')[0].reset();
						  $('#updateModal').modal('hide');
					  },
					  error: function (data) {
					  }
				  });
				}
			});		
				
		   //delete student
			$('body').on('click', '.btnDelete', function () {
			  var student_id = $(this).attr('data-id');
			  $.get('student/delete/'+student_id, function (data) {
				  $('#studentTable tbody #'+ student_id).remove();
			  })
		   });	
			
		});	  
	</script>
</div>
</body>
</html>

Step 7: Run The ApplicationNow we will run our example using the below Url in the browser.

http://localhost/codeigniter4_ajax_crud/student

We think would you like this article, so you can click on the “Download” button and you can download this demo article.

Download

Please follow and like us:

Hope this code and post will helped you for implement Codeigniter 4 CRUD Operation With Ajax Example – onlinecode. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

  +  45  =  54

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US