How to use Ajax in CodeIgniter 3 with example

You can fetch data from the database and display it in an web page without reloading the page by using Ajax with CodeIgniter 3. It is not difficult to use Ajax in this case, if you have already used it with custom PHP.

In this topic, we will create a simple application to show how you can use Ajax in CodeIgniter 3. This application can display a list of courses with their details. For each course, it can display a detailed description of the course in a modal after an Ajax call. This application also shows how you can display dynamic data in a Bootstrap modal.

Step 1 - Create a table in MySQL database for course details

We will create a table 'training_courses' in MySQL database. This table will have course details, like course name, price etc. Table structure is given below:

Table: training_courses

codeigniter with ajax

Below are the columns in this table.

  1. course_id - Unique course id, primary key and auto incremented
  2. course_name - Name of the course
  3. price - Price of the course
  4. course_details - Detail description of the course

training_courses.sql


CREATE TABLE `training_courses` (
  `course_id` int(11) NOT NULL,
  `course_name` varchar(255) NOT NULL,
  `price` decimal(8,2) NOT NULL,
  `course_details` varchar(500) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


INSERT INTO `training_courses` (`course_id`, `course_name`, `price`, `course_details`) VALUES
(1, 'Beginners\' course in PHP', '500.00', 'This course is aimed for persons who do not have any knowledge in PHP. It starts with the basics of PHP and then move into the writing program in PHP. Also, it gives an overview of HTML and CSS which are prerequisite to learn PHP. This is a 2 months training program and very well organized for a beginner. If you are looking for a training program in PHP, this course is the best for you.'),
(2, 'HTML and CSS', '400.00', 'This course provides the learning knowledge in HTML and CSS. It starts with basics and aimed for beginners and provides basic HTML and CSS along with Bootstrap and some basics of JavaScript. This is a one-month program where students will have ample opportunity to do practical. Trainers are very experienced and very organized to make sure every student gets his/her question answered. Go for this course if you want to start your career in web development.'),
(3, 'Java Language', '500.00', 'This course provides basic of Object-Oriented Programming and starts with basic Java Program. If you have some knowledge in any programming language it will be easier for you to start this course. This is 2 months training program. You will learn OOP programming style, class, object, Java Library, string functions. Also, there will be project work each student has to complete to have more practical knowledge in Java.'),
(4, 'Python and Django', '600.00', 'This course is for students who want to learn Python. This course provides an in-depth knowledge in Python program including Django framework. It is a one-month program. Prerequisite required for this course is: basic knowledge in HTML, CSS, JavaScript and MySQL. There are lot of hands-on works and you will complete the course with a Project.');

ALTER TABLE `training_courses`
  ADD PRIMARY KEY (`course_id`);

ALTER TABLE `training_courses`
  MODIFY `course_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;

We will be using a folder named 'course' under xampp/htdocs for our application. So, the root directory for the project is xampp/htdocs/course.

Step 2 - Create the view to display list of courses (view_course.php)

The view displays the list of a courses with links to display detail description of each course. There is a custom css file for the styles. Below is a list of courses displayed.

How to send Ajax request in CodeIgniter 3

It is a simple html table where we are displaying details of each course in a for-loop. Let's see the code for the view:

application/views/view_course.php


<!DOCTYPE html>
<html lang="en">
<head>
  <title>Course List</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <link rel="stylesheet" href="<?php echo base_url('assets/css/style.css') ?>">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
  <script src="<?php echo base_url('assets/js/modal_scripts.js') ?>"></script>
</head>
<body>
  <div class="container">
    <h3>Training Courses</h3>
    <div class="table-responsive">
      <table class="table table-bordered table-striped">
        <tr>
          <thead>
            <th>Course Id</th><th>Course Name</th><th>Price</th><th>Course Details</th>
          </thead>
        </tr>
        <?php
        $counter = 0;
        if (!empty($course_data)) {
          foreach ($course_data as $row) { 
            $counter++?>
            <tr>
              <td><?php echo $row->course_id;?></td>
              <td><?php echo $row->course_name;?></td>
              <td><span class="fa fa-usd"> <?php echo $row->price;?></span></td>
              <td>
                <a href="javascript:void(0)" data-toggle="modal" data-target="#showDetails" class="view" data-id="<?php echo $row->course_id;?>" >View Details</a></td>
              </td>
            </tr>
          <?php } 
        }
        else { ?>
          <tr><td colspan="7">No Courses found</td></tr>
        <?php } ?>
      </table>
    </div>
    <!-- Modal to display the details of course -->
    <div id="showDetails" class="modal fade course" role="dialog">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">×</button>
            <h2>View Course Details</h2>
          </div>
          <div class="modal-body">
            
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-info" data-dismiss="modal">Close</button>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

All courses are selected from training_courses table and displayed data row by row in a html table. Look at the last column of the table which is "Course Details". A modal is called (this modal is defined later) with a parameter as course_id using data-id attribute. This id will be accessed by jQuery for Ajax call.

There is a modal defined here in line 44. Note that modal body is empty now, we will fetch the data using Ajax call and display the detail in modal body. When user clicks on "View Details", we will send AJAX request to display the content here.

There is a custom stylesheet used in the views. It is given below:

assets/css/style.css


h3{
  text-align: center;
  margin-top: 20px;
}
h2{
  text-align: center;
  width: 100%;
  }
table{
  width:80%;
}
table,th,td {
  margin:auto;
  border-collapse: collapse;
  border:1px solid #c4b2b2;
  }
thead {
  background-color: #265159;
  color:#fff;

}
thead,tbody {
  text-align: center;
}
.course .modal-body{
	height:351x;
	overflow-y:auto;
}
.course .modal-body p{
	line-height:26px;
	margin-top:20px;
}
.modal-dialog .modal-header {
	display:block;
}

Step 3 - Write Ajax Scripts (modal_scripts.js)

Code in modal_script.js takes the course_id value sent to the modal and using that it sends a Ajax request to get the details of the course. Once details are received as Ajax response, it displays the data in the modal. Let's see the code below:

assets/js/modal_scripts.js


// To display details in modal
$(document).on("click", ".view", function () {
     var courseId = $(this).data('id');
     $.ajax({
       url:'get_course_details',
       type: 'post',
       data: {course_id:courseId},
       dataType:'text',
       success: function(response){
              $(".modal-body").html(response);
            },
       error: function (request, status, error) {
        $(".modal-body").html(request.responseText);
          }
    });
});

It makes an Ajax call to get data from database. Parameters of Ajax are:

url: get_course_details - call to the controller method get_course_details() to get details of the course from database. It is defined in the route, see later.
type: post - Post method is used
data: {course_id:courseId} - course id sent to the request
dataType: text - output of Ajax call is text only
success: On success, write the output (response) from the controller method in the modal.
In case of any error we just need to print the error in the modal.

Step 4 - Write Controller code (CourseController.php)

Our controller class will have an index() method to display the courses and get_course_details() method which is called by Ajax.

Controller method index()

index() method is executed by default in a controller. In this method it calls a model method get_course() to get all courses and loads the view "view_course" with the course data.


public function index(){
	$data['course_data'] = $this->ModelCourse->get_course();
	$this->load->view('view_course',$data);
	}

It calls a model method get_course() to get all courses from database table in an array $data[] and loads the "view_course" view with $data[].

Controller Method get_course_details()

When user clicks on "View Details" link for a course, this method is called from Ajax with course_id as parameter. It gets the details of the course and displays course_name, course_details and price. This output goes as the response and displayed in the modal. See the code below:


public function	get_course_details(){
	$course_id = $this->input->post('course_id');
	$result = $this->ModelCourse->get_course($course_id);
	// foreach ($course_details as $row)
	echo "

Course Name: ".$result[0]->course_name."

"; echo "

".$result[0]->course_details."

"; echo "

Price: ".$result[0]->price."

"; }

Step 5 - Write Model code (ModelCourse.php)

get_course() method.

application/models/ModelCourse.php


class ModelCourse extends CI_Model {
  function __construct() {
    parent::__construct();
  }

  function get_course($course_id = "") {
    $this->db->select('*');
    $this->db->from('training_courses');
    if ($course_id != "")
      $this->db->where('course_id',$course_id);
    $query = $this->db->get();
    return $query->result();
  }
}

get_course() method has an optional course_id parameter, if course_id has a value, it selects data from training_courses table for the course_id. But if course_id is blank, it selects all courses from the table.

Step 6 - Update Configuration files and Test the Application

  1. Update autoload.php (application/config/autoload.php)

    Add 'database' in autoload libraries.

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

    Also, 'url' are added in helper array.

    
     $autoload['helper'] = array('url');
    
  2. Update config file (application/config/config.php)

    Update 'base_url' and 'index_page' as below in this file:

    
    $config['base_url'] = 'http://localhost/course/';
    
    
    $config['index_page'] = '';
    
  3. Update database.php in application/config folder with database name, userid as "root "and password as blank.
  4. Routes file (application/config/routes.php)
    
    $route['default_controller'] = 'CourseController';
    $route['404_override'] = '';
    $route['translate_uri_dashes'] = FALSE;
    
    $route['get_course_details'] = 'CourseController/get_course_details';
    
  5. Update .htaccess (hypertext access) file
    
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]
    

Test The Application

Run localhost/course in the browser. You will see the training courses page displayed as below:

How to use ajax in CodeIgniter 3

You can see the course details are displayed. For each course there is a "View Details" link at the end. Click on "View Details" of any course, you can see the modal opened with the course details and price displayed on it. See below when I clicked on PHP course:

How to call ajax in CodeIgniter 3

How to use ajax in CodeIgniter 3Important Note

We have used Bootstrap Modal which is very easy and simple to use. We have also used font-awesome library from CDN. This is used to display "$" sign.

jquery Ajax call Codeigniter ControllerConclusion

In this example, we have seen how you can use Ajax with CodeIgniter 3. This is also an example of displaying dynamic data in a Bootstrap modal. You can use it anywhere in your project for similar requirements. I hope it will be useful to you.