CRUD with codeigniter jquery and ajax

CRUD(Create, Read, Update ,Delete) is very important part of any dynamic web applications. The jquery and ajax is help load data from database server without reload and refresh the web application. Reload of web application it’s take more time as compare to the ajax. In the CRUD generally add records, display records from database and then update, delete records. AJAX (Asynchronous Javascript And XML) is a method or technique of web-based programming to create interactive web application. Sending data without reload page with Jquery Ajax. This tutorial also use bootstrap modal popup for inserting data and editing data.

  • we need to create a controller.

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

class Main_controller extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */

	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);
	}

}
  • we need to create a  view.
<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>
  • we need to create a  Model.
<?php
 /**
 * 
 */
 class Data_m extends CI_Model
 {
 	
 	public function showallData()
 	{
 		# code...
 		$query= $this->db->get('tbl_data');
 		if ($query->num_rows()>0) {
 			# code...
 			return $query->result();
 		}
 		else{
 				return false;
 		}
 	}

 	public function addData()
 	{
 		# code...
 		$field  = array('name' => $this->input->post('textName'), 
 					'address'=> $this->input->post('address'),
 					'created_at'=>date('Y-m-d H:i:s')
 			);
 		$this->db->insert('tbl_data', $field);
 		if ($this->db->affected_rows() >0) {
 			# code...
 			return true;
 		}
 		else{
 			return false;
 		}

 	}


 	public function editData()
 	{
 		# code...
 		$id=$this->input->get('id');
 		$this->db->where('id',$id);
 		$query= $this->db->get('tbl_data');
 		if ($query->num_rows() >0) {
 			# code...
 			return $query->row();
 		}
 		else
 		{
 			return false;
 		}
 	}



 	public function updateData()
 	{
 		# code...
 		$id = $this->input->post('txtID');
 		$field  = array('name' => $this->input->post('textName'), 
 					'address'=> $this->input->post('address'),
 					'updated_at'=>date('Y-m-d H:i:s')
 			);


 		$this->db->where('id',$id);
 		$this->db->update('tbl_data', $field);
 		

 		if ($this->db->affected_rows() >0) {
 			# code...
 			return true;
 		}
 		else{
 			return false;
 		}

 	}

 	public function deleteData()
 	{
 		# code...
 		$id = $this->input->get('id');

 		$this->db->where('id', $id);
 		$this->db->delete('tbl_data');
 		if ($this->db->affected_rows() >0) {
 			# code...
 			return true;
 		}
 		else{
 			return false;
 		}

 	}





 }
  • show all Data From database

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.');

					}

			});
		}
  • add new new

$('#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');
		}
	});

});
  • Delete

$('#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');
			}
		});

	});