Dependent dropdown using Codeigniter and Jquery Ajax

Dependent dropdown using Codeigniter and Jquery Ajax

The following HTML code contains dependent dropdowns for countries and states. Country options are read from the database and shown in the dropdown on page load. Initially, the state dropdown has no options. On changing the country dropdown values, a jQuery function is called to get dependent state options and loaded dynamically.

In HTML

 

<div class="form-group">
	<select name="country" id="country" class="form-control country">
		<option value="">Select Country</option>
		<?php foreach ($country as $key => $c): ?>
			<option value="<?php echo $c['id']; ?>"><?php echo $c['country_name']; ?></option>
		<?php endforeach ?>
	</select>
</div>
<div class="form-group city_area" style="display: none;">
	<select name="city" id="city" class="form-control city">
		<option value="">Select City</option>
	</select>
</div>

 

In Controller

 

public function get_city($id){
        $city = $this->common_model->get_city($id);

        if (count($city) != '') {
        	foreach ($city as $row) {
	            echo ''.$row["city_name"].'';
	        }
        }else {
        	$text = "Sorry City Not Found";
	        echo ''.$text.'';
        }

 }

 

In Model

 

public function get_city($id)
{
	$this->db->select('c*');
	$this->db->from('city as c');
	$this->db->where('c.country_id',$id);
	$query = $this->db->get();
	if($query->num_rows() == 1) {
		return $query =$query->result_array();
	}else{
		return false;
	}
	
	
}

 

In Jquery

 

$('.country').change(function(){
    var id = $(this).val();
    if(id != ''){
        var url = base_url+'welcome/get_city/'+ id;
        $.get(url,{ },function(data){
            $('.city').html(data);
            $('.city_area').slideDown();
        });
    }else{
         $('.city').html('Select City');
         $('.city_area').slideUp();
    }

});