How to use Ajax in CodeIgniter 3 with example

Using Ajax with CodeIgniter 3 you can fetch data from database without refresing the page. It is not difficult to use Ajax in this case, if you already have used it in PHP.

In this topic, we will create a simple application to show how you can use Ajax in CodeIgniter 3. Send AJAX request in CodeIgniter 3 and data will be fetched from database via a controller method and will be displayed in a modal.This application can display a list of courses with their details. For each course, it can display the detailed description of the course in a modal(fetching data using Ajax call) when user clicks a link. The application is developed using CodeIgniter 3 with Ajax and MySQL. I will assume you have basic knowledge of CodeIgniter 3, MySQL and Ajax.

Step 1 - Create a table in MySQL database for courses

Let us create a table named 'training_courses' in MySQL database. This table will have course details, like course name, price etc. I have a database called 'demo'. So, this table will be created in demo database. Table structure is given below:

Table: training_courses

This table stores details of all training courses.

codeigniter with ajax

Below are the columns in this table.

  1. course_id - It is unique id of the course, 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
Create table script for this table is given below; you can use this code to create the table.

training_courses.sql

After you create the table, verify if table structure is same as above and the rows are inserted in the table. Rows in the table should be as below:

ajax in codeigniter 3 tutorial

Before I go to next step, let me show the folder structure I am using. I have created a folder named 'course' under xampp/htdocs and kept all CodeIgniter folder/files in this folder along with our custom files. So, the root directory is xampp/htdocs/course.

how to get ajax post data in codeigniter controller

You can see, we have Controller - CourseController.php, Model - ModelCourse.php and the view (view_course.php) under views folder. Folder 'assets' is created to keep all custom stylesheets, JavaScripts and image files. Here we have css/style.css and js/modal_scripts.js for our application.

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 I am displaying details of each course in a for loop. Controller sends the course data to the view and using a for loop each course is displayed. Let's see the code for the view:

application/views/view_course.php

All courses are selected from training_courses database table and displayed data row by row in a html table. Look at the table data for 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 45. 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 in CodeIgniter 3 to display the content here.

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

assets/css/style.css

I just added few simple styles here, you can always add better styles.

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

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

url: get_course_details - request call to the controller method get_course_details() of 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: When Ajax successfully gets response, we 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.

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 as a Ajax request with course_id as parameter. It gets the details of the course and just displays course_name, course_details and price. This output goes as the response and displayed in the modal. See the code below:

You can see it calls the same model method get_course(), but with a parameter course_id. It returns a single row for the course_id.

Our controller methods are done, next let us see the methods in the model.

Step 5 - Write Model code (ModelCourse.php)

We have seen only one method of the model used in the controller. This is get_course(). So now let's see the code for this method in the model:

application/models/ModelCourse.php

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.

Our views, controller and models are developed. Now we need to do some setup changes before we run the application. Let's do that in next step.

Step 6 - Update Configuration files and Test the Application

We will update below files in config folder:

Config files for Ajax in CodeIgniter

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

    I have added 'database' in autoload libraries.

    Also, 'url' are added in helper array.

  2. Update config file (application/config/config.php)

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

  3. Update database setup file (application/config/database.php)

    As I mentioned before, I am using a database named 'demo' in localhost with user 'root' and blank password, so I updated database.php as below:

  4. Update routes file (application/config/routes.php) I updated `routes.php for default controller which is CourseController and also added a route for the ajax request.
  5. Update .htaccess (hypertext access) file to remove index.php from the URL

    .htaccess file is used to do configuration changes for a directory. I have kept .htaccess file in my root folder which is xampp/htdocs/course.

    htaccess file form Ajax in CodeIgniter

    Content of .htaccess file is given below:

    Using URL rewriting rule, it redirects all request except those which are not existing files or directories.

Test The Application

Make sure in your XAMPP control panel Apache and MySQL services are running. Open the browser and run localhost/course. You will see the training courses page displayed as below:

How to send data using ajax in CodeIgniter

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 in it. See below when I clicked on PHP course:

How to check ajax request in CodeIgniter 3

Our development and testing are done. Hope you could understand all the steps and could test it successfully.

How to use ajax in CodeIgniter 3Important Note

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

How to submit form using ajax in CodeIgniter 3Download Code

I have put codes for controller, model and view in a zip file. You can download it by clicking on the Download button below. You do not need to register yourself to download it. You can use the code as is or you can modify them as per your requirements.

jquery Ajax call Codeigniter ControllerConclusion

In this example I have showed you how you can display data in a modal using Ajax in CodeIgniter 3. Using modal is a very good option to display information to the user. It gives better user experience. You can use it anywhere in your project for similar requirement.