php onchange 使用 ajax、codeigniter、dropdown

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21229791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:56:01  来源:igfitidea点击:

onchange using ajax, codeigniter, dropdown

phpajaxcodeigniteronchange

提问by Rebecca

I am facing a problem with onchange event in codeigniter...I am showing a country state onchange event but the value of the country is taken zero due to which it is not changing the states accordingly.

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

Controller:

控制器:

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

?>

Model:

模型:

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

View:

看法:

    <!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

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

回答by Nouphal.M

First of all in your controller there is no function names get_statesas you call in your ajax. There is only get_citiesfunction. Either you have to change the ajax call to get_cities or rename the function.

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

Then If you are not getting the selected option with $('#country').val() ,then try

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

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

OR

或者

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

Next you have to specify the dataTypeto json in ajax function to treat the response as json.

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

Controller function

控制器功能

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

View

看法

$('#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);
               });
        },
    });
});