loading

How to CodeIgniter CRUD Operations without Page Refresh using jQuery and Ajax

How to CodeIgniter CRUD Operations without Page Refresh using jQuery and Ajax

How to CodeIgniter CRUD Operations without Page Refresh using jQuery and Ajax

0 Sales

Free

CRUD Operations are the most often used web application capability in CodeIgniter. CodeIgniter CRUD (Create, Read, Update, and Delete) actions are used to manipulate data in the database (Fetch, Insert, Update, and Delete). When an action is requested in a CodeIgniter CRUD application, the page is often refreshed and forwarded. CRUD activities are also done in CodeIgniter without the need for a page refresh by utilising jQuery and Ajax.

If you really want to create the CodeIgniter CRUD feature more user-friendly, incorporate it without requiring a page reload. In this topic, we'll teach you how to use jQuery and Ajax to provide CRUD features in CodeIgniter without having to refresh the page. The sample script demonstrates how to use jQuery, Ajax, and MySQL to incorporate data management features (view, add, edit, and delete) into the CodeIgniter 3 framework.

The following features will be added to a CodeIgniter CRUD application built using Bootstrap 4 with jQuery, Ajax, and MySQL.

 - Get the members' information from the database and display it on the web page.
 - Fill up the blanks in the database with member information.
 - In the database, you may edit and update member information.
 - Delete the database's member data.
 - The add/edit/delete procedures will function on a single page without requiring a page refresh.

 

Take a look at the file structure before beginning to construct a CodeIgniter AJAX CRUD application.

codeigniter_ajax_crud/
├── application/
│   ├── controllers/
│   │   └── Members.php
│   ├── models/
│   │   └── Member.php
│   └── views/
│       ├── templates/
│       │   ├── header.php
│       │   └── footer.php
│       └── members/
│           ├── index.php
│           └── view.php
└── assets/
    ├── css/
    ├── js/
    ├── images/
    └── bootstrap/

Create Database Table

A table in the database must be built in order to store and manage the data. In the MySQL database, the following SQL creates a members table with some basic columns.

CREATE TABLE `members` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
 `last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `gender` enum('Male','Female') COLLATE utf8_unicode_ci NOT NULL,
 `country` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Config

autoload.php
Define the widely used library and helper to run regularly on every session in the config/autoload.php file.

$autoload['libraries'] = array('database');
$autoload['helper'] = array('url');

Controller (Members.php)

The Members controller handles CRUD activities (view, add, edit, and remove) depending on the AJAX POST request.

1. __construct() – Loads the Member model in order to conduct database-related tasks.
2. index() – Using the getRows() function, retrieve all member records from the database and give the data to the view for listing.
3. memData() – Retrieve a single member's data from the database using their ID. The member data is returned in JSON format.

4. listView() – Retrieve all member information from the database. The data is returned in HTML format.
5. add()

       - Get the data from the form fields that were sent via AJAX request.
       - Validate the form fields you've filled out.
       - Using the insert() function of the Member model, enter the member data into the database.
       - Returns the AJAX response in JSON format.

6. edit()

       - Retrieve and verify the data from the form fields that was submitted through AJAX request.
       - The update() function of the Member model is used to update member data in the database depending on the ID.
       - Returns the AJAX response in JSON format.

7. delete()

       - Using the ID obtained by the AJAX session, remove membership data from the database.
       - The value is returned in JSON format.

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

class Members extends CI_Controller {
    
    function __construct() {
        parent::__construct();
        
        // Load member model
        $this->load->model('member');
    }
    
    public function index(){
        $data = array();
        
        // Get rows count
        $conditions['returnType']     = 'count';
        $rowsCount $this->member->getRows($conditions);
        
        // Get rows
        $conditions['returnType'] = '';
        $data['members'] = $this->member->getRows($conditions);
        $data['title'] = 'Members List';
        
        // Load the list page view
        $this->load->view('templates/header'$data);
        $this->load->view('members/index'$data);
        $this->load->view('templates/footer');
    }
    
    public function memData(){
        $id $this->input->post('id');
        if(!empty($id)){
            // Fetch member data
            $member $this->member->getRows(array('id'=>$id));
            
            // Return data as JSON format
            echo json_encode($member);
        }
    }

    public function listView(){
        $data = array();
        
        // Fetch all records
        $data['members'] = $this->member->getRows();
            
        // Load the list view
        $this->load->view('members/view'$data);
    }
    
    public function add(){
        $verr $status 0;
        $msg '';
        $memData = array();
        
        // Get user's input
        $first_name $this->input->post('first_name');
        $last_name $this->input->post('last_name');
        $email $this->input->post('email');
        $gender $this->input->post('gender');
        $country $this->input->post('country');
        
        // Validate form fields
        if(empty($first_name) || empty($last_name)){
            $verr 1;
            $msg .= 'Please enter your name.<br/>';
        }
        if(empty($email) || !filter_var($emailFILTER_VALIDATE_EMAIL)){
            $verr 1;
            $msg .= 'Please enter a valid email.<br/>';
        }
        if(empty($country)){
            $verr 1;
            $msg .= 'Please enter your country.<br/>';
        }
        
        if($verr == 0){
            // Prepare member data
            $memData = array(
                'first_name'=> $first_name,
                'last_name'    => $last_name,
                'email'        => $email,
                'gender'    => $gender,
                'country'    => $country
            );
            
            // Insert member data
            $insert $this->member->insert($memData);
            
            if($insert){
                $status 1;
                $msg .= 'Member has been added successfully.';
            }else{
                $msg .= 'Some problem occurred, please try again.';
            }
        }
        
        // Return response as JSON format
        $alertType = ($status == 1)?'alert-success':'alert-danger';
        $statusMsg '<p class="alert '.$alertType.'">'.$msg.'</p>';
        $response = array(
            'status' => $status,
            'msg' => $statusMsg
        );
        echo json_encode($response);
    }
    
    public function edit(){
        $verr $status 0;
        $msg '';
        $memData = array();
        
        $id $this->input->post('id');
        
        if(!empty($id)){
            // Get user's input
            $first_name $this->input->post('first_name');
            $last_name $this->input->post('last_name');
            $email $this->input->post('email');
            $gender $this->input->post('gender');
            $country $this->input->post('country');
            
            // Validate form fields
            if(empty($first_name) || empty($last_name)){
                $verr 1;
                $msg .= 'Please enter your name.<br/>';
            }
            if(empty($email) || !filter_var($emailFILTER_VALIDATE_EMAIL)){
                $verr 1;
                $msg .= 'Please enter a valid email.<br/>';
            }
            if(empty($country)){
                $verr 1;
                $msg .= 'Please enter your country.<br/>';
            }
            
            if($verr == 0){
                // Prepare member data
                $memData = array(
                    'first_name'=> $first_name,
                    'last_name'    => $last_name,
                    'email'        => $email,
                    'gender'    => $gender,
                    'country'    => $country
                );
                
                // Update member data
                $update $this->member->update($memData$id);
                
                if($update){
                    $status 1;
                    $msg .= 'Member has been updated successfully.';
                }else{
                    $msg .= 'Some problem occurred, please try again.';
                }
            }
        }else{
            $msg .= 'Some problem occurred, please try again.';
        }
        
        // Return response as JSON format
        $alertType = ($status == 1)?'alert-success':'alert-danger';
        $statusMsg '<p class="alert '.$alertType.'">'.$msg.'</p>';
        $response = array(
            'status' => $status,
            'msg' => $statusMsg
        );
        echo json_encode($response);
    }
    
    public function delete(){
        $msg '';
        $status 0;
        
        $id $this->input->post('id');
        
        // Check whether member id is not empty
        if(!empty($id)){
            // Delete member
            $delete $this->member->delete($id);
            
            if($delete){
                $status 1;
                $msg .= 'Member has been removed successfully.';
            }else{
                $msg .= 'Some problem occurred, please try again.';
            }
        }else{
            $msg .= 'Some problem occurred, please try again.';
        }  
        
        // Return response as JSON format
        $alertType = ($status == 1)?'alert-success':'alert-danger';
        $statusMsg '<p class="alert '.$alertType.'">'.$msg.'</p>';
        $response = array(
            'status' => $status,
            'msg' => $statusMsg
        );
        echo json_encode($response);
    }
}

 

Model (Member.php)

The database operations are handled by the Member model (Fetch, Add, Edit, and Delete).

1. __construct() – Give the table a name.
2. getRows() – Retrieve the members data from the database depending on the parameters supplied in $params. If successful, returns the data array; otherwise, returns FALSE.
3. insert() – Enter member information into the database. If successful, returns the row ID; otherwise, returns FALSE.
4. update() – Using the row ID, update member data in the database. If the function is successful, it returns TRUE; otherwise, it returns FALSE.
5. delete() – Using the row ID, delete the record from the database. If the function is successful, it returns TRUE; otherwise, it returns FALSE.

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

class Member extends CI_Model{
    
    function __construct() {
        // Set table name
        $this->table 'members';
    }
    
    /*
     * Fetch members data from the database
     * @param array filter data based on the passed parameters
     */
    function getRows($params = array()){
        $this->db->select('*');
        $this->db->from($this->table);
        
        if(array_key_exists("conditions"$params)){
            foreach($params['conditions'] as $key => $val){
                $this->db->where($key$val);
            }
        }
        
        if(array_key_exists("returnType",$params) && $params['returnType'] == 'count'){
            $result $this->db->count_all_results();
        }else{
            if(array_key_exists("id"$params)){
                $this->db->where('id'$params['id']);
                $query $this->db->get();
                $result $query->row_array();
            }else{
                $this->db->order_by('first_name''asc');
                if(array_key_exists("start",$params) && array_key_exists("limit",$params)){
                    $this->db->limit($params['limit'],$params['start']);
                }elseif(!array_key_exists("start",$params) && array_key_exists("limit",$params)){
                    $this->db->limit($params['limit']);
                }
                
                $query $this->db->get();
                $result = ($query->num_rows() > 0)?$query->result_array():FALSE;
            }
        }
        
        // Return fetched data
        return $result;
    }
    
    /*
     * Insert members data into the database
     * @param $data data to be insert based on the passed parameters
     */
    public function insert($data = array()) {
        if(!empty($data)){
            // Add created and modified date if not included
            if(!array_key_exists("created"$data)){
                $data['created'] = date("Y-m-d H:i:s");
            }
            if(!array_key_exists("modified"$data)){
                $data['modified'] = date("Y-m-d H:i:s");
            }
            
            // Insert member data
            $insert $this->db->insert($this->table$data);
            
            // Return the status
            return $insert?$this->db->insert_id():false;
        }
        return false;
    }
    
    /*
     * Update member data into the database
     * @param $data array to be update based on the passed parameters
     * @param $id num filter data
     */
    public function update($data$id) {
        if(!empty($data) && !empty($id)){
            // Add modified date if not included
            if(!array_key_exists("modified"$data)){
                $data['modified'] = date("Y-m-d H:i:s");
            }
            
            // Update member data
            $update $this->db->update($this->table$data, array('id' => $id));
            
            // Return the status
            return $update?true:false;
        }
        return false;
    }
    
    /*
     * Delete member data from the database
     * @param num filter data based on the passed parameter
     */
    public function delete($id){
        // Delete member data
        $delete $this->db->delete($this->table, array('id' => $id));
        
        // Return the status
        return $delete?true:false;
    }
}

 

Views

1. templates/

The views/templates/ directory contains the web page's element sections (header, footer, etc.).

1.1. templates/header.php

The header.php file contains the web page's header.

 - In CodeIgniter, jQuery and Ajax are utilised to conduct CRUD tasks without refreshing the page, thus add the jQuery library.
 - Bootstrap is used to create a modal dialogue popup to a web page as well as style the data table, form fields, and links. Include the Bootstrap 4 CSS and JS library files.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title><?php echo $title?> | CodeIgniter CRUD without Page Refresh</title>
    
    <!-- jQuery library -->
    <script src="<?php echo base_url('assets/js/jquery.min.js'); ?>"></script>
    
    <!-- Bootstrap library -->
    <link rel="stylesheet" href="<?php echo base_url('assets/bootstrap/bootstrap.min.css'); ?>">
    <script src="<?php echo base_url('assets/bootstrap/bootstrap.min.js'); ?>"></script>
    
    <!-- Stylesheet file -->
    <link rel="stylesheet" href="<?php echo base_url('assets/css/style.css'); ?>">
</head>
<body>

1.2. templates/footer.php

The footer.php file contains the web page's footer.

</body>
</html>

2. members/
The views/members/ directory contains the Members controller's view files.

2.1. members/index.php
This view displays all of the member's information in a tabular manner and handles CRUD (View, Add, Edit/Update, and Delete) requests with jQuery and Ajax.

HTML Code:

Initially, the member's data is retrieved from the database and shown in an HTML table with Edit and Delete buttons.

 - An Insert link is placed at the top of the data list to commence the generate call.
 - When you press the Add button, a Bootstrap modal popup with an HTML form to add a new member displays.
 - When you click the Edit button, a Bootstrap modal popup with the HTML form and pre-filled data displays, allowing you to amend the member's data.
 - A confirmation window comes when you click the Delete button. Following approval, a delete request is sent to the database to remove the record.

<div class="container">
    <!-- Display status message -->
    <div class="statusMsg"></div>
    
    <div class="row">
        <div class="col-md-12 head">
            <h5><?php echo $title?></h5>
            <!-- Add link -->
            <div class="float-right">
                <a href="javascript:void(0);" class="btn btn-success" data-type="add" data-toggle="modal" data-target="#modalUserAddEdit"><i class="plus"></i> New Member</a>
            </div>
        </div>
    
        <!-- Data list table --> 
        <table class="table table-striped table-bordered">
        <thead class="thead-dark">
            <tr>
                <th>#</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Email</th>
                <th>Gender</th>
                <th>Country</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody id="userData">
            <?php if(!empty($members)){ foreach($members as $row){ ?>
            <tr>
                <td><?php echo $row['id']; ?></td>
                <td><?php echo $row['first_name']; ?></td>
                <td><?php echo $row['last_name']; ?></td>
                <td><?php echo $row['email']; ?></td>
                <td><?php echo $row['gender']; ?></td>
                <td><?php echo $row['country']; ?></td>
                <td>
                    <a href="javascript:void(0);" class="btn btn-warning" rowID="<?php echo $row['id']; ?>" data-type="edit" data-toggle="modal" data-target="#modalUserAddEdit">edit</a>
                    <a href="javascript:void(0);" class="btn btn-danger" onclick="return confirm('Are you sure to delete data?')?userAction('delete', '<?php echo $row['id']; ?>'):false;">delete</a>
                </td>
            </tr>
            <?php } }else{ ?>
            <tr><td colspan="7">No member(s) found...</td></tr>
            <?php ?>
        </tbody>
        </table>
    </div>
</div>


<!-- Modal Add and Edit Form -->
<div class="modal fade" id="modalUserAddEdit" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <!-- Modal Header -->
            <div class="modal-header">
                <h4 class="modal-title"><span id="hlabel">Add New</span> Member</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            
            <!-- Modal Body -->
            <div class="modal-body">
                <div class="statusMsg"></div>
                <form role="form">
                    <div class="form-group">
                        <label>First name</label>
                        <input type="text" class="form-control" name="first_name" id="first_name" placeholder="Enter first name" >
                    </div>
                    <div class="form-group">
                        <label>Last name</label>
                        <input type="text" class="form-control" name="last_name" id="last_name" placeholder="Enter last name" >
                    </div>
                    <div class="form-group">
                        <label>Email</label>
                        <input type="text" class="form-control" name="email" id="email" placeholder="Enter email" >
                    </div>
                    <div class="form-group">
                        <label>Gender</label>
                        <div class="custom-control custom-radio custom-control-inline">
                            <input type="radio" id="gender1" name="gender" class="custom-control-input" value="Male" checked="checked" >
                            <label class="custom-control-label" for="gender1">Male</label>
                        </div>
                        <div class="custom-control custom-radio custom-control-inline">
                            <input type="radio" id="gender2" name="gender" class="custom-control-input" value="Female" >
                            <label class="custom-control-label" for="gender2">Female</label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Country</label>
                        <input type="text" class="form-control" name="country" id="country" placeholder="Enter country" >
                    </div>
                    <input type="hidden" class="form-control" name="id" id="id"/>
                </form>
            </div>
            
            <!-- Modal Footer -->
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-success" id="userSubmit">SUBMIT</button>
            </div>
        </div>
    </div>
</div>

JavaScript Code:

The JavaScript code below handles Ajax requests using the CodeIgniter application.

1. getUsers() – Using the jQuery $.post() function, retrieve the members data from the Members controller (members/listView). When the operation is successful, the content of the member data list is updated with the response data.
2. userAction() – Using jQuery and Ajax, send add, edit, and remove requests to the Members controller (members/add | members/edit | members/delete). When the operation is successful, the response message is displayed to the user.
3. editUser() – Using jQuery and Ajax, retrieve a specified member data from the Members controller (members/memData). Set the appropriate value in the form fields if the test is successful.
4. shown.bs.modal – Based on the add/edit request, this Bootstrap modal event is utilised to alter the data-type attribute value.

      - If an Add request is made, the userAction() function is assigned to the onclick element of the submit button (#userSubmit) with the add argument. If an Edit request is made, userAction() is set to the onclick attribute of the submit button (#userSubmit) with the edit parameter. In addition, the editUser() method is used to pre-fill the member's data in the modal form using the rowID.

5. hidden.bs.modal – The onclick property of the submit button (#userSubmit) is removed using this Bootstrap modal event. The pre-filled form data as well as the status message are also erased from the modal form and web page.

<script>
// Update the members data list
function getUsers(){
    $.post( "<?php echo base_url('members/listView/'); ?>", function( data ){
        $('#userData').html(data);
    });
}

// Send CRUD requests to the server-side script
function userAction(type, id){
    id = (typeof id == "undefined")?'':id;
    var userData = '', frmElement = '';
    if(type == 'add'){
        frmElement = $("#modalUserAddEdit");
        userData = frmElement.find('form').serialize();
    }else if (type == 'edit'){
        frmElement = $("#modalUserAddEdit");
        userData = frmElement.find('form').serialize();
    }else{
        frmElement = $(".row");
        userData = 'id='+id;
    }
    frmElement.find('.statusMsg').html('');
    $.ajax({
        type: 'POST',
        url: '<?php echo base_url('members/'); ?>'+type,
        dataType: 'JSON',
        data: userData,
        beforeSend: function(){
            frmElement.find('form').css("opacity", "0.5");
        },
        success:function(resp){
            frmElement.find('.statusMsg').html(resp.msg);
            if(resp.status == 1){
                if(type == 'add'){
                    frmElement.find('form')[0].reset();
                }
                getUsers();
            }
            frmElement.find('form').css("opacity", "");
        }
    });
}

// Fill the user's data in the edit form
function editUser(id){
    $.post( "<?php echo base_url('members/memData/'); ?>", {id: id}, function( data ){
        $('#id').val(data.id);
        $('#first_name').val(data.first_name);
        $('#last_name').val(data.last_name);
        $('#email').val(data.email);
        $('input:radio[name="gender"]').filter('[value="'+data.gender+'"]').attr('checked', true);
        $('#country').val(data.country);
    }, "json");
}

// Actions on modal show and hidden events
$(function(){
    $('#modalUserAddEdit').on('show.bs.modal', function(e){
        var type = $(e.relatedTarget).attr('data-type');
        var userFunc = "userAction('add');";
        $('#hlabel').text('Add New');
        if(type == 'edit'){
            userFunc = "userAction('edit');";
            var rowId = $(e.relatedTarget).attr('rowID');
            editUser(rowId);
            $('#hlabel').text('Edit');
        }
        $('#userSubmit').attr("onclick", userFunc);
    });
    
    $('#modalUserAddEdit').on('hidden.bs.modal', function(){
        $('#userSubmit').attr("onclick", "");
        $(this).find('form')[0].reset();
        $(this).find('.statusMsg').html('');
    });
});
</script>

2.2. members/view.php

This view, which is utilised by the Members controller's listView() function, displays the members' data in HTML format.

<?php if(!empty($members)){ foreach($members as $row){ ?>
<tr>
    <td><?php echo $row['id']; ?></td>
    <td><?php echo $row['first_name']; ?></td>
    <td><?php echo $row['last_name']; ?></td>
    <td><?php echo $row['email']; ?></td>
    <td><?php echo $row['gender']; ?></td>
    <td><?php echo $row['country']; ?></td>
    <td>
        <a href="javascript:void(0);" class="btn btn-warning" rowID="<?php echo $row['id']; ?>" data-type="edit" data-toggle="modal" data-target="#modalUserAddEdit">edit</a>
        <a href="javascript:void(0);" class="btn btn-danger" onclick="return confirm('Are you sure to delete data?')?userAction('delete', '<?php echo $row['id']; ?>'):false;">delete</a>
    </td>
</tr>
<?php } }else{ ?>
<tr><td colspan="7">No member(s) found...</td></tr>
<?php ?>

Conclusion

Our CodeIgniter and MySQL sample AJAX CRUD application will assist you in implementing data management features in the CodeIgniter framework without the need for page refreshes and reloads. To manage data in the database, the user does not need to visit the pages. Using jQuery and Ajax, you can implement the add, edit, update, and delete functions with the MySQL database. The CRUD operations of CodeIgniter's sample Ajax CRUD application may be simply incorporated without page refresh using jQuery.

LICENSE OF USE

You can use it for personal or commercial projects. You can't resell it partially or in this form.

PRODUCT INFO

Create Date : Feb 12, 2022

Updated Date : Feb 12, 2022

Ratings

Comments : 0

Downloads : 0