2013-09-19 2 views
0

Я следил за этим tutorial, чтобы заполнить два моих города и сражаться, я хочу отфильтровать названия городов в соответствии с выбранным названием страны. Я использую CodeIngniter 2.1.4 и jquery-1.10.2 и базу данных postgreSQL.заполнить два выпадающего списка с помощью CodeIngniter & ajax

, но я не получаю города и страны: выпадающий пуст

пользователя Контроллер

<?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))); 
} 

} 
?> 
<?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; 
     } 
} 

} 
?> 

CountryModel:

<?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; 
       } 
     } 

} 
?> 

post_view.php

<html> 

     <head> 
       <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/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/codeingiter/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> 

всякая помощь приветствуется.

+0

пожалуйста, посмотрите на мой [ответ] (http://stackoverflow.com/ вопросы/5072299/chain-select-with-category-and-sub-category-in-codeigniter/18012611 # 18012611) для цепочечных selectboxes, я думаю, что его путь проще. Также обратите внимание, что вам нужно также отлаживать JavaScript (в chrome Element Inspector, в FF FireBug) – Kyslik

+0

спасибо за ваш ответ, я это увижу; FireBug не возвращает мне никаких ошибок. –

+0

@ Таргуя Мохамед решается? –

ответ

0

этот код Перезапишите проходящее значение переменной, поэтому изменить его

function get_cities($country = null){ 

изменение его как:

function get_cities($country){ 

    /*your query here */ 

    } 
Смежные вопросы