Cascading Drop Down in Codeigniter Using AJAX

In this article, I am explaining how to create a cascading dropdown in codeigniter using ajax.

Introduction to CodeIgniter

We will be using CodeIgniter, which has been described as "a powerful PHP framework with a very small footprint".
CodeIgniter is a PHP-driven framework, containing a grab-bag of libraries, helpers, plug-ins and other resources, that takes care of many of the more complex procedures and functions for which PHP is famous. CodeIgniter does all the heavy lifting for you while maintaining high performance. It will simplify PHP syntax, streamline the code underlying your web pages and best of all, have you churning out dynamic, interactive, professional websites in no time.

Principles of CodeIgniter
  1. It makes coding in PHP simple, quick and user-friendly.

  2. It's an excellent framework for learning more about how PHP works as you code.

  3. It follows the Model/View/Controller (MVC) approach to web development.

  4. It's built on a linear, easy-to-use folder structure.

  5. It's open source and simple to configure and customize for your own needs.

  6. You can construct your own cleaner URI lines in CodeIgniter.
In my previous article I showed how to fetch data from a database in codeignitor and the required settings of codeignitor: Fetch Data From Database and Show in Tabular Format in Codeigniter.
 
Now here I am explaining cascading dropdown in codeignitor that belong together and if I select country from the dropdown then the cities in the selected country will be automatically shown in another dropdown without post-back. Now here I am explaining cascading dropdown in codeignitor that belong together and if I select the country in the dropdown then the cities in that selected country will be automatically shown in the other dropdown without post-back.

Step 1:
 This is my database table that I have given the name "category".

 
Step 2:  
This is my cities table that I have given the name
"sub_category".
 
 

The "cat_id" column is the foreign key column that is referenced from the "category" table's column "cat_id". 
 
Step 3Database connectivity

You must first edit the file database.php that can be found in the application/config/ folder. The important changes are:
  1. $db['default']['hostname'] = 'localhost';  
  2. $db['default']['username'] = 'root';  
  3. $db['default']['password'] = '';  
  4. $db['default']['database'] = 'abc';  
  5. $db['default']['dbdriver'] = 'mysql';   
Step 4: Autoload the database

If your application uses the database very much then you need to change the autoload.php that can also be found inside the application/config/ folder.
  1. $autoload['libraries'] = array('database');   
Step 5: By default, CodeIgniter has one primary config file, located at application/config/config.php.
  1. $config['base_url'] = 'http://localhost/cascading/';   
Cascading is the folder where my application is present.
 
Step 6: The Model

In the Models we have the CRUD operations. I will create a model named "cities_countries_model.php".
  1. <?php  
  2. class Cities_countries_model extends CI_Model {  
  3.    public function __construct()  
  4.    {  
  5.       $this->load->database();  
  6.    }  
  7.    //fill your contry dropdown  
  8.    public function getCountries()  
  9.    {  
  10.       $this->db->select('cat_id,category');  
  11.       $this->db->from('category');  
  12.       $query = $this->db->get();  
  13.       // the query mean select cat_id,category from  
  14.       category  
  15.       foreach($query->result_array() as $row){  
  16.          $data[$row['cat_id']]=$row['category'];  
  17.       }  
  18.       // the fetching data from database is return  
  19.       return $data;  
  20.    }  
  21.    //fill your cities dropdown depending on the selected city  
  22.    public function getCityByCountry($cat_id=string)  
  23.    {  
  24.       $this->db->select('sub_id,sub_name');  
  25.       $this->db->from('sub_category');  
  26.       $this->db->where('cat_id',$cat_id);  
  27.       $query = $this->db->get();  
  28.       return $query->result();  
  29.    }  
  30. }  
Step 7: The Controller

I will create a Controller named "countries.php". 
  1. <?php  
  2.    class Countries extends CI_Controller {  
  3.    public function __construct()  
  4.    {  
  5.       parent::__construct();  
  6.       $this->load->database();  
  7.       $this->load->helper('url');  
  8.       $this->load->helper('form');  
  9.       $this->load->model('cities_countries_model');  
  10.    }  
  11.    public function index()  
  12.    {  
  13.       //starts by running the query for the countries  
  14.       dropdown  
  15.       $data['countryDrop'] = $this-  
  16.       >cities_countries_model->getCountries();  
  17.       //loads up the view with the query results  
  18.       $this->load->view('cascadeDrop'$data);  
  19.    }  
  20.    //call to fill the second dropdown with the cities  
  21.    public function buildDropCities()  
  22.    {  
  23.       //set selected country id from POST  
  24.       echo $id_country = $this->input->post('id',TRUE);  
  25.       //run the query for the cities we specified earlier  
  26.       $districtData['districtDrop']=$this-  
  27.       >cities_countries_model->getCityByCountry($id_country);  
  28.       $output = null;  
  29.       foreach ($districtData['districtDrop'as $row)  
  30.       {  
  31.          //here we build a dropdown item line for each  
  32.          query result  
  33.          $output .= "<option value='".$row-  
  34.          >sub_name."'>".$row->sub_name."</option>";  
  35.       }  
  36.       echo $output;  
  37.    }  
  38. }  
Step 8: The View 

To display the output we need a view named "cascadeDrop.php". The code will go something like this:
  1. <html xmlns="http://www.w3.org/1999/xhtml">  
  2.    <head>  
  3.       <meta http-equiv="Content-Type" content="text/html;  
  4.       charset=utf-8" />  
  5.       <title>cascade drops example</title>  
  6.          <script type="text/javascript"  
  7.             src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.  
  8.             min.js"></script>  
  9.             <script type="text/javascript"  
  10.                src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquer  
  11.                y-ui.min.js"></script>  
  12.                <script type="text/javascript">  
  13.                   $(document).ready(function() {  
  14.                      $("#countriesDrp").change(function(){  
  15.                      /*dropdown post *///  
  16.                      $.ajax({  
  17.                         url:"<?php echo  
  18.                         base_url();?>index.php/countries/buildDropCities",  
  19.                         data: {id:  
  20.                            $(this).val()},  
  21.                         type: "POST",  
  22.                         success:function(data){  
  23.                         $("#cityDrp").html(data);  
  24.                      }  
  25.                   });  
  26.                });  
  27.             });  
  28.          </script>  
  29.       </head>  
  30.    <body>  
  31.       <!--country dropdown-->  
  32.       <?php echo form_dropdown('countriesDrp',  
  33.       $countryDrop,'','class="required" id="countriesDrp"'); ?>  
  34.       <br />  
  35.       <br />  
  36.       <!--city dropdown-->  
  37.       <select name="cityDrp" id="cityDrp">  
  38.          <option value="">Select</option>  
  39.       </select>  
  40.       <br />  
  41.    </body>  
  42. </html>  
On the beginning of the view file we have a jQuery script that will enable us to do the post, it starts with checking if all the elements are ready and loaded, next it listens to the "selected" event from the country dropdown, that is the trigger for the post.

When the event is raised a ajax "request" (let's call it like this) is created and on it we specify all sorts of useful stuff:
  • URL: the destination of the request (on this example is the controller/function).

  • Data: the information we intend to add to the request (on this example the selected id value from the dropdown).

  • Type: request type (GET/POST).

  • Success: what happens if the request reaches it's destination. 
Output

The output will look like this:

program output