Ajax drop down for Country State & City in Codeigniter?

前端 未结 3 1070
温柔的废话
温柔的废话 2021-01-29 14:56

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

相关标签:
3条回答
  • 2021-01-29 15:29

    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.

    0 讨论(0)
  • 2021-01-29 15:43

    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

    0 讨论(0)
  • 2021-01-29 15:44
    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.

    0 讨论(0)
提交回复
热议问题