You can fetch data from the database and display it in a web page without reloading the whole 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 to 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 to display dynamic data in a Bootstrap modal.
Create a table in MySQL database for the course details
We will create a table 'training_courses' in MySQL database. This table will have course details, like course name, price, etc. The table structure is given below:
Table: training_courses
Below are the columns in this table.
course_id - Unique course id, primary key and auto incremented
course_name - Name of the course
price - Price of the course
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 use a folder named 'course' under xampp/htdocs for our application. So, the root directory for the project is xampp/htdocs/course.
Create the view to display list of courses (view_course.php)
The view displays the list of courses with links to display the detail description of each course. There is a custom CSS file for the styles. Below is a list of courses displayed.
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:
All courses are selected from the training_courses table and displayed data row by row in an html table. See 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 a data-id attribute. This id will be accessed by jQuery for Ajax call.
There is a modal defined here in line 44. Note that the modal body is empty now, we will fetch the data using an Ajax request and display the detail in the modal body. When the user clicks on "View Details", we will send an Ajax request to display the content here.
There is a custom stylesheet used in the view. It is given below:
Code in modal_script.js takes the course_id sent to the modal and sends an 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 the 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 the case of any error, we need to display the error in the modal.
Write Controller code (CourseController.php)
Our controller class will have an index() method to display the courses. It will have another method named get_course_details() to be used by Ajax.
Controller method index()
index() method calls a model method get_course() to get all the 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);
}
Controller Method get_course_details()
When a user clicks on the "View Details" link for a course, this method is called from Ajax with course_id as a parameter. It gets the details of the course and displays course_name, course_details and price. This output goes as the response and is 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."
";
}
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 the training_courses table for the course_id. But if course_id is blank, it selects all the courses from the database table.
Update Configuration files and Test the Application
Run localhost/course in the browser. You will see the training courses page displayed as below:
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 the PHP course:
Note
We have used Bootstrap Modal which is very easy and simple to use. We have also used the font-awesome library from CDN. This is used to display "$" sign.
Conclusion
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 in your project for similar requirements. I hope it will be useful to you.
Post a Comment