Home > CodeIgniter, php > Simple ajax drop down filtering with CodeIgniter

Simple ajax drop down filtering with CodeIgniter

Rather than using pure php, when it comes to a framework, working with ajax become much tricky. Since codeigniter using inbuilt MVC architecture, we have to consider the routing pattern of the application as well.

Suppose we want to filter city names according to the selected country name. Here is how we gonna do it.

Create two tables in the database. Countries and Cities.

Countries -> 2 fields (id, country_name) ; Cities ->  3 fields(id,city_name,country_id);

Create the User controller as follows.


<?php
class User extends CI_Controller {

public function __construct() {
 parent::__construct();
 $this -> load -> model('country_model');

}
 function Register() {
 $data['countries'] = $this -> country_model -> get_countries();
 $this -> load -> view('test/post_view', $data);
 }

 function get_cities($country){
 $this->load->model('city_model');
 header('Content-Type: application/x-json; charset=utf-8');
 echo(json_encode($this->city_model->get_cities($country)));
}

}

Add models.

city_model.php


<?php
class City_model extends CI_Model {

public function __construct() {
 $this -> load -> database();

}

function get_cities($country = null){
 $this->db->select('id, city_name');

 if($country != NULL){
 $this->db->where('country_id', $country);
 }

 $query = $this->db->get('cities');

 $cities = array();

 if($query->result()){
 foreach ($query->result() as $city) {
 $cities[$city->id] = $city->city_name;
 }
 return $cities;
 }else{
 return FALSE;
 }
}

}
?>

country_model.php


<?php
class Country_model extends CI_Model {

public function __construct() {
 $this -> load -> database();

}

function get_countries() {
 $this -> db -> select('id, country_name');
 $query = $this -> db -> get('countries');

$countries = array();

if ($query -> result()) {
 foreach ($query->result() as $country) {
 $countries[$country -> id] = $country -> country_name;
 }
 return $countries;
 } else {
 return FALSE;
 }
 }

}
?>

Then create the view.


<html>

 <head>
 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 <script type="text/javascript">// <![CDATA[
 $(document).ready(function(){
 $('#country').change(function(){ //any select change on the dropdown with id country trigger this code
 $("#cities > option").remove(); //first of all clear select items
 var country_id = $('#country').val(); // here we are taking country id of the selected one.
 $.ajax({
 type: "POST",
 url: "http://localhost/test/user/get_cities/"+country_id, //here we are calling our user controller and get_cities method with the country_id

 success: function(cities) //we're calling the response json array 'cities'
 {
 $.each(cities,function(id,city) //here we're doing a foeach loop round each city with id as the key and city as the value
 {
 var opt = $('<option />'); // here we're creating a new select option with for each city
 opt.val(id);
 opt.text(city);
 $('#cities').append(opt); //here we will append these new select options to a dropdown with the id 'cities'
 });
 }

 });

 });
 });
 // ]]>
</script>
 </head>
<body>
<?php $countries['#'] = 'Please Select'; ?>

<label for="country">Country: </label><?php echo form_dropdown('country_id', $countries, '#', 'id="country"'); ?><br />
 <?php $cities['#'] = 'Please Select'; ?>
<label for="city">City: </label><?php echo form_dropdown('city_id', $cities, '#', 'id="cities"'); ?><br />
</body>
</html>

Now when you choose the country, the relevant cities are automatically filtered.

Like bellow.

country : India

City : Mumbai, Kolkatta

when you select country as Sri Lanka,

City : Colombo, Matara

Advertisements
Categories: CodeIgniter, php
  1. March 13, 2013 at 1:06 pm

    Reblogged this on RJ Solusoft.

  2. Vipul Patil
    March 19, 2013 at 8:13 am

    hey nice tutorial ,,but facing some trouble ,,,I am getting the values in first dropdown but no effect is occuring on 2nd dropdown,,,,, please cousel me where I am wrong?

    • supun dharmarathne
      March 19, 2013 at 8:29 am

      U should use the full url correctly. is dat so ? here is the complete code
      http://pastebin.com/prVjXGTJ take a look…

  3. Vipul Patil
    March 19, 2013 at 10:05 am

    there is no model for country man……

  4. April 7, 2013 at 4:19 am

    After checking out a few of the blog articles
    on your blog, I seriously like your way of blogging.

    I bookmarked it to my bookmark website list
    and will be checking back in the near future.

    Please visit my web site as well and tell me your
    opinion.

  5. April 9, 2013 at 1:48 am

    Greetings! Very useful advice in this particular article!

    It is the little changes that will make the most important changes.
    Many thanks for sharing!

  6. Darshana
    May 17, 2013 at 9:01 am

    I did the same thing but i don’t get cities can u please show me how route change

  7. November 30, 2013 at 4:41 am

    In the above database tables you used ID both the tables is that id values are identical in both tables and to my surprise I find a country_id field in cities table but not in countries table and Finally, when i tried the above code I’m getting empty country and cities. Hope this will helpful to me

  8. November 30, 2013 at 4:42 am

    Suresh Mallarapu :
    In the above database tables you used ID both the tables is that id values are identical in both tables and to my surprise I find a country_id field in cities table but not in countries table and Finally, when i tried the above code I’m getting empty country and cities. Hope this will helpful to me

    Suresh Mallarapu :
    In the above database tables you used ID both the tables is that id values are identical in both tables and to my surprise I find a country_id field in cities table but not in countries table and Finally, when i tried the above code I’m getting empty country and cities. Hope this will helpful to me

    Suresh Mallarapu :
    In the above database tables you used ID both the tables is that id values are identical in both tables and to my surprise I find a country_id field in cities table but not in countries table and Finally, when i tried the above code I’m getting empty country and cities. Hope this will helpful to me

  9. January 27, 2014 at 11:47 pm

    The Register function gives me a 404 error. I changed it to index but when I select country, no cities show up.,

  10. Helloworld
    August 17, 2014 at 11:35 am

    I tried copy everything and created the db with the same description as above mentioned. Unfortunately the code above is not working. I did not get the city name when I changed the country.

  11. September 1, 2014 at 4:26 am

    excellent job! code works very well.but i have one issue. after dropdown how to display all data in table.after filter how to change data.
    i have one car table.table fields are carname, manufacture,city,fueltype, transmission .so how i can display filter data.

  12. Pradip Debnath
    November 17, 2014 at 11:05 am

    This code is not working.

    • Nils
      November 28, 2014 at 10:39 am

      Yes it does, I used and transform it, it works.
      (Even if I do not understand it all.)

  13. Nils
    November 28, 2014 at 10:37 am

    Hi,

    for which line or char is set CDATA in the JS script ?

    Is it for the line var opt = $(”); ?

    Why tag and not tag ?
    Where is the opening tag ?

    I do not understand :

    var opt = $(”);
    opt.val(id_course);
    opt.text(lieu_depart);

    Thanks, Nils.

  14. Nils
    November 28, 2014 at 10:56 am

    An other time with CDATA as tags has been removed (just a try).

    <![CDATA[
    Hi,

    for which line or char is set CDATA in the JS script ?

    Is it for the line var opt = $('’); ?

    Why tag and not tag ?
    Where is the opening tag ?

    I do not understand :

    var opt = $(”);
    opt.val(id_course);
    opt.text(lieu_depart);

    Thanks, Nils.
    ]]>

    Please remove this post if no change (tags removed as well).

  15. ahmed Hassan
    January 12, 2015 at 4:25 am

    thanks alot this code it is very good
    but there are something i hope to make if i select country and this country has no city i hope to put message like no city rather than empty

  16. ahmed Hassan
    January 12, 2015 at 4:29 am

    thanks alot it is very good code but i hope to make when i select country and this country has no city put message like no city

  17. Maya
    February 27, 2015 at 5:35 am

    Thank you 😀

  18. admin
    July 10, 2015 at 9:02 am

    very bad code..

  19. Nasir
    September 8, 2015 at 11:22 am

    Problem in the dropdown… Udefined form_dropdown….

  20. Nasir
    September 8, 2015 at 11:37 am

    i have just loaded the form helper and its good to go..thanks

  21. hassan
    May 9, 2016 at 9:37 pm

    i want to make # value to be disabled how can i do this?

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: