onchange使用ajax,codeigniter,下拉列表

时间:2014-01-20 08:59:17

标签: php ajax codeigniter onchange

我在codeigniter中遇到onchange事件的问题...我正在显示一个国家/地区状态onchange事件,但该国家/地区的值为零,因此它没有相应地改变状态。

控制器:

    <?php
    class countries extends CI_Controller {
   public function __construct()
   { 
            parent::__construct();
    $this->load->database();
    $this->load->helper('form');
    $this->load->helper('url');
    $this->load->model('countries_model');

    $this -> load -> model('country_model');
    $this -> load -> model('state_model');

}

public function index()
{
$this->data['countries'] = $this -> country_model -> get_countries();
  $view_data = array();
  $this->display_data();
$this->load->view('view', $this->data);
}


    public function get_states(){
        log_message('debug', 'Inside uController :get_states');
        log_message('debug', 'Value of country is '+$this->input->post('country_id'));
        log_message('debug', 'Value of country is '+$this->input->post('data'));
        var_dump(data);
        $country=$this->input->post('country');
        //echo $country;

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


public function dataupdate()
{
      $i=$this->input->post('country_id');
    $s=$this->input->post('state_id');
        $this->model->UpdateData();
        $this->load->view('success');
    }

?>

型号:

    <?php
   class Countries_model extends CI_Model {
   public function __construct()
{

    parent::__construct();

}
    public function get_countries()
   {

    log_message('debug', ' poc_dropdown ######################################################inside model ');
    $query ="SELECT * FROM MCountry";

    $query_result = $this->db->query($query);
    log_message('debug', ' poc_dropdown ######################################################calling db query ');
    $data = array();
    foreach($query_result->result() as $row){
        $data[] = $row;
    }
    return $data;
}
}

     function UpdateData($dt)
{
$id=$this->input->post('pk');

 $data=array(
      'Col_Country'=>$this->input->post('country_id'),
    'Col_State'=>$this->input->post('state_id'),
       );
  $this->db->where('pk',$id);
  $this->db->update('User',$data);
     }
?>

查看:

    <!DOCTYPE html>
    <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        
                  alert("inside country");
                  // $("#states > option").remove();
                    $("#states > option").remove();
                    alert("inside country2");
                    //$("#cities > option").remove();   //first of all clear select items.
                alert($('#country').val());
                    var country_id = {
                            //alert("inside country3");
                            //country:$('#country').val()
                            country:$('#country option:selected').val()  
                            //alert("inside country4");
                    };  // here we are taking country id of the selected one.

                    alert(country_id);
                    $.ajax({
                        type: "POST",
                        url: "<?php echo site_url('u/get_states'); ?>", //here we are calling our user controller and get_cities method with the country_id
                        data:country_id,
                        datatype : "json",
                        success: function(states) //we're calling the response json array 'states'
                        {

                            $.each(states,function(id,state) //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(state);
                                $('#states').append(opt); //here we will append these new select options to a dropdown with the id 'states'
                            });
                        }

                    });

                });

            });
    </script>

    <tr><th><label for="country">Country: </label></th><td>
             <?php $countries['#'] = 'Please Select'; ?>

                <?php echo form_dropdown('country_id', $countries, '#', 'id="country"','name="country"'); ?>
                </td></tr>

    <tr><th> <label for="state">State: </label> </th><td>
                 <?php $states['#'] = 'Please Select'; ?>
                <?php echo form_dropdown('state_id', $states, '#', 'id="states"','name="states"'); ?>
                </td></tr>

State_model:

    <?php
   class state_model extends  CI_Model {

    public function __construct() {

            $this -> load -> database();

    }

    function get_states($country){//


  $this->db->select('pkMState, State');

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

  $query = $this->db->get('MState');
 // $d=$query->result();
  $states = array();

  if($query->result()){
      foreach ( $query->result() as $state) {  //$query->result()

         $states[$state -> pkMState] = $state -> State;
      }
  return   $states;
  }
  else{
     return 0;
  }

    }
    }

   ?>

Country_model

public function get_countries() {

            $this -> db -> select('pkCountry, CountryName');
            $query = $this -> db -> get('MCountry');

            $countries = array();

            if ($query -> result()) {
                    foreach ($query->result() as $country) {
                            $countries[$country -> pkCountry] = $country -> CountryName;
                    }
                    return $countries;
            } else {
                    return 0;
            }
    }

1 个答案:

答案 0 :(得分:2)

首先在您的控制器中,您在ajax中调用时没有函数名get_states。只有get_cities功能。您必须将ajax调用更改为get_cities或重命名该函数。

然后如果您没有使用$('#country')。val()获取所选选项,请尝试

$('#country option:selected').val()  

OR

   $(this).find(':selected').val()

接下来,您必须在ajax函数中指定dataType到json,以将响应视为json。

控制器功能

 public function get_cities(){
        log_message('debug', 'Value of country is '+$this->input->post('country_id'));
        $country=$this->input->post('country');
        $this->load->model('state_model');
        $states = array();
        $states = $this->state_model->get_states($country);
        echo json_encode($states);
  }

查看

$('#country').change(function(){
    $.ajax({
        type: "POST",
        url: "<?php echo site_url('countries/get_cities'); ?>", 
        data:country_id,
        dataType:"json",//return type expected as json
        success: function(states){
               $.each(states,function(key,val){
                    var opt = $('<option />'); 
                    opt.val(key);
                    opt.text(val);
                    $('#states').append(opt);
               });
        },
    });
});