onchange using ajax, codeigniter, dropdown

24,116

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

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

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

OR

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

Next you have to specify the dataType to json in ajax function to treat the response as 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);
               });
        },
    });
});
Share:
24,116
Rebecca
Author by

Rebecca

I work as a PHP Developer from December 2013, and have experience with core PHP , Codeigniter, Jquery, Javascript etc.

Updated on November 25, 2022

Comments

  • Rebecca
    Rebecca over 1 year

    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.

    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

    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;
                }
        }
    
    • Renier
      Renier over 10 years
      What is u/ in url: "<?php echo site_url('u/get_states'); ?>"?
    • Rebecca
      Rebecca over 10 years
      @Renier: changed it to the appropriate controller name(u is also one of my controller)
  • Rebecca
    Rebecca over 10 years
    @Nauphal.M : it does not help,i get the same issue...the value is not passed into the controller,i get the value as 0 which is wrong
  • Nouphal.M
    Nouphal.M over 10 years
    you controller function name is wrong. Check the updated answeer
  • Rebecca
    Rebecca over 10 years
    Hey @Nouphal...am actually using country,state,city function and applying an onchange,so got a bit confused but yes i have put the right names in my original query but to paste a short code i post only two functions of state and country...i will make the necessary changes... Still i dont get the value and it shows as [object Object] in my alert...my logs show 0 as value
  • Nouphal.M
    Nouphal.M over 10 years
    log_message('debug', 'Value of country is '+$this->input->post('country'));
  • Rebecca
    Rebecca over 10 years
    the value gives me 0 in the log files...should give me the selected country [email protected]