How to create a Dynamic dropdown in CodeIgniter 3 using AJAX

To create a dynamic dropdown in CodeIgniter 3 using AJAX, you'll need to follow these steps:

Step 1: Set Up Your CodeIgniter Project.

If you haven't already, create a new CodeIgniter project or use an existing one. Ensure that your project structure is properly set up.

Step 2: Create a Database Table.

Create a database table that stores the data you want to populate in your dynamic dropdown. For this example, let's assume you have a table named categories with columns id and name.

Step 3: Configure Database Connection.

Configure your database connection in the database.php configuration file application/config/database.php with your database credentials.

$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'your_db_username',
    'password' => 'your_db_password',
    'database' => 'your_db_name',
    'dbdriver' => 'mysqli',
    // ...
);

Step 4: Create a Controller.

Create a controller that will handle AJAX requests and load the view.

// application/controllers/CategoryController.php

class CategoryController extends CI_Controller {
    
    public function index() {
        $this->load->view('category_view');
    }

    public function getCategories() {
        // Load the model that interacts with the database
        $this->load->model('CategoryModel');

        // Get categories from the model
        $categories = $this->CategoryModel->getCategories();

        // Send categories as JSON response
        $this->output->set_content_type('application/json')->set_output(json_encode($categories));
    }
}

Step 5. Create a Model.

Create a model to interact with the database and fetch categories.

// application/models/CategoryModel.php

class CategoryModel extends CI_Model {

    public function getCategories() {
        $query = $this->db->get('categories');
        return $query->result_array();
    }
}

Step 6: Create a View.

Create a view where you'll display the dynamic dropdown.

<!-- application/views/category_view.php -->

<!DOCTYPE html>
<html>
<head>
    <title>Dynamic Dropdown Example</title>
    <!-- Include jQuery library -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h1>Dynamic Dropdown Example</h1>
    
    <select id="categoryDropdown">
        <option value="">Select Category</option>
    </select>

    <script type="text/javascript">
        $(document).ready(function() {
            // Function to populate the dropdown
            function populateDropdown() {
                $.ajax({
                    url: "<?php echo site_url('categorycontroller/getCategories'); ?>",
                    type: "GET",
                    dataType: "json",
                    success: function(data) {
                        var dropdown = $('#categoryDropdown');
                        dropdown.empty(); // Clear the dropdown

                        // Add the default option
                        dropdown.append('<option value="">Select Category</option>');

                        // Loop through data and add options to the dropdown
                        $.each(data, function(key, entry) {
                            dropdown.append($('<option></option>').attr('value', entry.id).text(entry.name));
                        });
                    }
                });
            }

            // Call the function to populate the dropdown
            populateDropdown();

            // Trigger the function when the page loads or when needed
            // You can use events like onchange of another dropdown or button click
        });
    </script>
</body>
</html>

In this view, we use jQuery to make an AJAX request to the getCategories method in the CategoryController. The response (a list of categories) is then used to populate the dropdown dynamically.

Step 7: Route Configuration.

Make sure to configure your routes in routes.php (application/config/routes.php) to map the controller methods.

$route['default_controller'] = 'categorycontroller';
$route['categorycontroller/getCategories'] = 'categorycontroller/getCategories';

Step 8: Test Your Application.

Access your application in a web browser, and you should see the dynamic dropdown populated with categories from the database.

This is a basic example of creating a dynamic dropdown in CodeIgniter 3 using AJAX. You can further enhance this by adding error handling, validation, and integrating it into your application as needed.

Muhammad Alfaiz
Alfaiz 6 months ago
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x