Thursday 11 March 2021

Dynamic Dependent Dropdown using Ajax in Codeigniter 4



This is Codeigniter 4 tutorial on Dynamic dependent dropdown using Ajax. This is furthermost tutorial on Dynamic dependent select box in Codeigniter 4 with Ajax jQuery. Dynamically dependent select box is mainly used in the country state and city selection or category and sub category option selection, we have used on the web page. And under this dynamic dependent dropdown list box child field data changes according to the value of it's parent field.

For make dynamic dependent select box or dropdown, we have to use Ajax jQuery with Codeigniter 4 framework. So in this post, we have make dynamic dependent select box in Codeigniter 4 using Ajax jQuery. Here you can find step by step guide for build how to create dynamic dependent select box in Codeigniter 4 using Ajax with jQuery, Mysql and Bootstrap 4 library.


Dynamic Dependent Dropdown using Ajax in Codeigniter 4


Codeigniter 4 Dynamic Dependent dropdown with Ajax


  1. Download Codeigniter 4 framework
  2. Create Table in Mysql Database
  3. Setup Mysql Database Connection
  4. Create Model File
  5. Create Controller
  6. Create View File
  7. Start Codeigniter 4 Server

Step 1 - Download Codeigniter 4 framework


In this step, you have to download the latest version of Codeigniter 4 framework. Here we will use composer for download Codeigniter 4 framework. So for this, we have to go command prompt, and then after go to directory in which you want to download and install codeigniter 4 framework and here we want to run following command.


composer create-project codeigniter4/appstarter dynamic-dependent


This command will make dynamic-dependent directory and under that directory it will download and install Codeigniter 4 framework.

Step 2 - Create Table in Mysql Database


In this step, we need to make database with name testing. So, we have to open PHPMyAdmin and under this we have to create database with name testing. And after successfully create database, we have to run following sql script for creating required table in database.


--
-- Database: `country_state_city`
--

-- --------------------------------------------------------

--
-- Table structure for table `country`
--

CREATE TABLE `country` (
  `country_id` int(11) NOT NULL,
  `country_name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `country`
--

INSERT INTO `country` (`country_id`, `country_name`) VALUES
(1, 'USA'),
(2, 'Canada'),
(3, 'Australia'),
(4, 'India');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `country`
--
ALTER TABLE `country`
  ADD PRIMARY KEY (`country_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `country`
--
ALTER TABLE `country`
  MODIFY `country_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;

--
-- Table structure for table `state`
--

CREATE TABLE `state` (
  `state_id` int(11) NOT NULL,
  `country_id` int(11) NOT NULL,
  `state_name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `state`
--

INSERT INTO `state` (`state_id`, `country_id`, `state_name`) VALUES
(1, 1, 'New York'),
(2, 1, 'Alabama'),
(3, 1, 'California'),
(4, 2, 'Ontario'),
(5, 2, 'British Columbia'),
(6, 3, 'New South Wales'),
(7, 3, 'Queensland'),
(8, 4, 'Karnataka'),
(9, 4, 'Telangana');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `state`
--
ALTER TABLE `state`
  ADD PRIMARY KEY (`state_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `state`
--
ALTER TABLE `state`
  MODIFY `state_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;

--
-- Table structure for table `city`
--

CREATE TABLE `city` (
  `city_id` int(11) NOT NULL,
  `state_id` int(11) NOT NULL,
  `city_name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `city`
--

INSERT INTO `city` (`city_id`, `state_id`, `city_name`) VALUES
(1, 1, 'New York city'),
(2, 1, 'Buffalo'),
(3, 1, 'Albany'),
(4, 2, 'Birmingham'),
(5, 2, 'Montgomery'),
(6, 2, 'Huntsville'),
(7, 3, 'Los Angeles'),
(8, 3, 'San Francisco'),
(9, 3, 'San Diego'),
(10, 4, 'Toronto'),
(11, 4, 'Ottawa'),
(12, 5, 'Vancouver'),
(13, 5, 'Victoria'),
(14, 6, 'Sydney'),
(15, 6, 'Newcastle'),
(16, 7, 'City of Brisbane'),
(17, 7, 'Gold Coast'),
(18, 8, 'Bangalore'),
(19, 8, 'Mangalore'),
(20, 9, 'Hydrabad'),
(21, 9, 'Warangal');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `city`
--
ALTER TABLE `city`
  ADD PRIMARY KEY (`city_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `city`
--
ALTER TABLE `city`
  MODIFY `city_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;





Step 3 - Setup Mysql Database Connection


In third step, we have need to connect our Codeigniter 4 application with Mysql database. For this, we have to open app/Config/Database.php file in your text editor. And After opening of that file in texteditor, we have to define database configuration details, which we can seen below.


public $default = [
		'DSN'      => '',
		'hostname' => 'localhost',
		'username' => 'root',
		'password' => '',
		'database' => 'testing',
		'DBDriver' => 'MySQLi',
		'DBPrefix' => '',
		'pConnect' => false,
		'DBDebug'  => (ENVIRONMENT !== 'production'),
		'cacheOn'  => false,
		'cacheDir' => '',
		'charset'  => 'utf8',
		'DBCollat' => 'utf8_general_ci',
		'swapPre'  => '',
		'encrypt'  => false,
		'compress' => false,
		'strictOn' => false,
		'failover' => [],
		'port'     => 3306,
	];





Step 4 - Create Model File


After making mysql database connection, next we have to go to app/Models folder and under this we have to create three model class file for each Country, State and city table which you can find below.

app/Models/CountryModel.php

<?php

//CountryModel.php

namespace App\Models;

use CodeIgniter\Model;

class CountryModel extends Model{

	protected $table = 'country';

	protected $primaryKey = 'country_id';

	protected $allowedFields = ['country_name'];

}	

?>


app/Models/StateModel.php

<?php

//StateModel.php

namespace App\Models;

use CodeIgniter\Model;

class StateModel extends Model{

	protected $table = 'state';

	protected $primaryKey = 'state_id';

	protected $allowedFields = ['country_id', 'state_name'];

}	

?>


app/Models/CityModel.php

<?php

//CityModel.php

namespace App\Models;

use CodeIgniter\Model;

class CityModel extends Model{

	protected $table = 'city';

	protected $primaryKey = 'city_id';

	protected $allowedFields = ['state_id', 'city_name'];

}

?>





Under this all file, we have to define Mysql table name, table primary key and field name details in all model for database related operation using Model class.

Step 5 - Create Controller


In this steps, we have to create controller class for handle http request. So for create Controllers class, we have to visit app/Controllers folder and create controller with name Dynamic_dependent.php. Under this controller class, we have need to add following method under this controller class.

app/Controllers/Dynamic_dependent.php

<?php

//Dynamic_dependent.php

namespace App\Controllers;

use App\Models\CountryModel;

use App\Models\StateModel;

use App\Models\CityModel;

class Dynamic_dependent extends BaseController
{
	function index()
	{
		$countryModel = new CountryModel();

		$data['country'] = $countryModel->orderBy('country_name', 'ASC')->findAll();

		return view('dynamic_dependent', $data);
	}

	function action()
	{
		if($this->request->getVar('action'))
		{
			$action = $this->request->getVar('action');

			if($action == 'get_state')
			{
				$stateModel = new StateModel();

				$statedata = $stateModel->where('country_id', $this->request->getVar('country_id'))->findAll();

				echo json_encode($statedata);
			}

			if($action == 'get_city')
			{
				$cityModel = new CityModel();
				$citydata = $cityModel->where('state_id', $this->request->getVar('state_id'))->findAll();

				echo json_encode($citydata);
			}
		}
	}
}

?>


Step 6 - Create View File


Under this step, we have to create view files with name dynamic_dependent.php under Views directory. This file will used for display html output in browser.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes">
    <link rel="stylesheet" href="<?php echo base_url('/css/bootstrap.min.css'); ?>" >
    <script src="<?php echo base_url('/js/jquery.min.js'); ?>"></script>
    <script src="<?php echo base_url('/js/popper.min.js'); ?>"></script>
    <script src="<?php echo base_url('/js/bootstrap.min.js'); ?>"></script>
    <title>Codeigniter 4 Dynamic Dependent Dropdown with Ajax</title>
</head>
<body>
    <div class="container">
        <h2 class="text-center mt-4 mb-4">Codeigniter 4 Dynamic Dependent Dropdown with Ajax</h2>
        <span id="message"></span>
        <div class="card">
            <div class="card-header">Codeigniter 4 Dynamic Dependent Dropdown with Ajax</div>
            <div class="card-body">
                <div class="row justify-content-md-center">
                    <div class="col col-lg-6">
                        <div class="form-group">
                            <select name="country" id="country" class="form-control input-lg">
                                <option value="">Select Country</option>
                                <?php
                                foreach($country as $row)
                                {
                                    echo '<option value="'.$row["country_id"].'">'.$row["country_name"].'</option>';
                                }
                                ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <select name="state" id="state" class="form-control input-lg">
                                <option value="">Select State</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <select name="city" id="city" class="form-control input-lg">
                                <option value="">Select City</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
 
</body>
</html>

<script>

$(document).ready(function(){

    $('#country').change(function(){

        var country_id = $('#country').val();

        var action = 'get_state';

        if(country_id != '')
        {
            $.ajax({
                url:"<?php echo base_url('/dynamic_dependent/action'); ?>",
                method:"POST",
                data:{country_id:country_id, action:action},
                dataType:"JSON",
                success:function(data)
                {
                    var html = '<option value="">Select State</option>';

                    for(var count = 0; count < data.length; count++)
                    {

                        html += '<option value="'+data[count].state_id+'">'+data[count].state_name+'</option>';

                    }

                    $('#state').html(html);
                }
            });
        }
        else
        {
            $('#state').val('');
        }
        $('#city').val('');
    });

    $('#state').change(function(){

        var state_id = $('#state').val();

        var action = 'get_city';

        if(state_id != '')
        {
            $.ajax({
                url:"<?php echo base_url('/dynamic_dependent/action'); ?>",
                method:"POST",
                data:{state_id:state_id, action:action},
                dataType:"JSON",
                success:function(data)
                {
                    var html = '<option value="">Select City</option>';

                    for(var count = 0; count < data.length; count++)
                    {
                        html += '<option value="'+data[count].city_id+'">'+data[count].city_name+'</option>';
                    }

                    $('#city').html(html);
                }
            });
        }
        else
        {
            $('#city').val('');
        }

    });

});

</script>


Step 7 - Start Codeigniter 4 Server


Now we have come on the last step, after follow all above step, now we need to start Codeigniter 4 framework server, so we have to command prompt and go into directory in which we have download and install Codeigniter framework, and then after we have to run following command.


php spark serve


This command will start Codeigniter 4 server and it will give us base url of our Codeigniter 4 application and for run above code, we have hit following url in browser.


http://localhost:8080/dynamic_dependent


Lastly, Under this post, we have make Codeigniter 4 Ajax dynamic dependent dropdown box. So after you have to follow above step you can successfully create Dynamic dependent dropdown in Codeigniter 4 with Ajax jQuery.

4 comments: