Ajax drop down for Country State & City in Codeign

2020-05-10 07:29发布

问题:

I am making country state and city drop down with the help of ajax in our codeigniter frame work .

The structure of database given bellow.

Country

country_id,country_name

State

country_id,state_id,state_name

city

country_id,state_id,city_id,city_name

user controler

function country(){
 $data['header']='Deal Management';
 $data['page'] = 'admin/page/user-view';
 $data['Country'] = $this->deal->getCountry(); 
 $this->load->view($this->_admin_container,$data);  
}

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

user-view View

<?php $cities['#'] = 'Please Select'; ?>

<label for="country">Country: </label><?php echo form_dropdown('country_id', $Country, '#', 'id="country"'); ?><br />

<label for="city">City: </label><?php echo form_dropdown('city_id', $cities, '#', 'id="cities"'); ?><br />

deal module country_modle

 function getCountry(){
    $this->db->select("*");
    $query=$this->db->get("deal_country");
    $countries = array();
    if($query->result()){
          foreach ($query->result() as $country) {
              $countries[$country->country_id] = $country->country_name;
          }
        return $countries;
        }else{
        return FALSE;
        }
    }

city_model Module

function get_cities($dealCountry = null){
        echo $dealCountry;die;
      $this->db->select('city_id, city_name');

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

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

      $cities = array();

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

I include ajax script in header file.

<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: "home/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(city_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>

After making code its not working .

Any help is appreciated!

Thanks

回答1:

create a javascript variable

var base_url = "<?=base_url()?>";

in your javascript code conecat it

url: base_url+"home/get_cities/"+country_id, 

use firefox and firebug to debug your ajax code



回答2:

As I have said in the comments, you can use Firebug or Chrome dev tools(network tab) to identify your problem:

Controller:

<?php
class ctrl extends ci_controller{
    function index(){ //I just used this one to test out if its outputing anything
        $names = ['apple','ball','cat','dog'];
        echo json_encode($names);
    }

    function load_view(){ 
        $this->load->view('ctrl_view');
    }
}
?>

View:

<script src="/tester/ci/js/jquery172.js"></script>
<input type="text" list="names" id="name" autocomplete="off"/>
<datalist id="names">
</datalist>

<script>
$.post('ctrl/', function(data){ //you can just call out your controller here
    var parsed_data = JSON.parse(data);

    //its a good practice to use a document fragment to append new elements to and not append a    new element on every iteration of the loop in an existing element in the dom
    var fragment = document.createDocumentFragment();

    for(var x in parsed_data){
        var val = parsed_data[x];
        var option = $("<option>").val(val).text(val);
        fragment.appendChild(option[0]); 
    }

    $('#names').append(fragment); //append the whole fragment outside the loop
});
</script>

I don't really know what your actual problem is so do us a favor, edit your question and paste what error you see on firebug.



回答3:

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

In this function, you put incorrect variable name $dealCountry.