populate dropdown from database in codeigniter

2019-06-05 18:40发布

问题:

I have a table in that table have 3 field (category1,category2,category3).Now i want to populate the Dropdown if dropdown one select ,dropdown 2 values will genarat from the data base . Can any one help me.

My Controller

            $this->load->model('quiz_mode');
            $arrStates = $this->quiz_mode->get_unique_catg1();

            foreach ($arrStates as $states)
            {
                $arrFinal[$category->category1 ] = $category->category1 ;
            }
            $data['category2'] = $arrFinal;
      function ajax_call() 
    {

        //Checking so that people cannot go to the page directly.
        if (isset($_POST) && isset($_POST['category1']))
        {

            $catogory = $_POST['category1'];
            $arrcategory = $this->sampl_mode->get_cities_from_catgo1($catogory);

            foreach ($arrcategory as $category)
            {
               $arrFinal[$category->category2] = $category->category2;
            }

            //Using the form_dropdown helper function to get the new dropdown.
            print form_dropdown('category2',$arrFinal);
        }
        else
        {
            redirect('logged_in_user'); //Else redire to the site home page.
        }
    }

My Model

function get_unique_catg1()
{

    $query = $this->db->query("SELECT DISTINCT category1  FROM sampl_table");

    if ($query->num_rows > 0) {
        return $query->result();
    }
}
    function get_cities_from_catgo1($category) {
    $query = $this->db->query("SELECT category2  FROM sampl_table WHERE category2 = '{$category}'");

    if ($query->num_rows > 0) {
        return $query->result();
    }
}

My view

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
    <title>untitled</title>

        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function () {

                $('#catgo1-dropdown').change(function () {
                    var selCat1 = $('#catgo1-dropdown').val();
                    console.log(selCat1);
                    $.ajax({
                        url: "<?php echo base_url();?>index.php/sample/ajax_call", //The url where the server req would we made.
                        async: false,
                        type: "POST", //The type which you want to use: GET/POST
                        data: "category1="+selCat1, //The variables which are going.
                        dataType: "html", //Return data type (what we expect).

                        //This is the function which will be called if ajax call is successful.
                        success: function(data) {
                            //data is the html of the page where the request is made.
                            $('#cotegory').html(data);
                        }
                    })
                });
            });
        </script>
</head>

    <body>
    <div id="wrapper">
                <div id="catgo1-dropdown"><?php print form_dropdown('category1'); ?></div>
                <div id="cotegory2"></div>

            </div>
    </body>

</html>

回答1:

There is a very simple solution for this

first only display first dropdown
then when user selects some value send it via ajax to a contrller method there the value will be recieved and passed to model.
in the model there should be query with where condition it will fetch results
Then back in controller call a view and pass query result to it
Your view should contain this code

<?php
foreach($queryresult as $row)
{
?>
<option value = "<?php echo $row->id?>"><?php echo $row->value;?</option>
<?php
}
?>

In you first view where there is a dropdown it should contain the following code

<select name = "first_drop_down" id = "first_drop_down" onchange = "calljavascriptfunction();">
<?php foreach($first_drop_down_values as $row){?>
<option value = "<?php echo $row->id?>"><?php echo $row->value;?</option>
<?php}?>

AND

 <select name = "second_drop_down" id = "second_drop_down" >
 <option value = "0">please select first dropdown</option>
 </select>

And ajax function

function calljavascriptfunction(){


  $.ajax({
     type : 'POST',
     data : 'first_drop_down_id='+ $('#first_drop_down').val(),
     url : 'controller/method',
     success : function(data){
                 $('#second_drop_down').val(data);
     }
 });
}

Done and here is a tutorial too

http://mikeheavers.com/index.php/site/code_single/dynamic_dependent_dropdown_filtering_with_codeigniter_and_jquery



回答2:

i used .html(msg); on div container of the dropdown

  <script type="text/javascript">
    $(document).ready(function() {  
    $('[name="wilaya"]').change(function () {  
            var input= this.value;
            //alert(input);
            $.ajax({
            url: "<?php echo base_url();?>/register/ajax_call",
            data: "input="+input
            })
            .done(function( msg ) {
            $(".commune").html(msg);
            }); }); 
      }); 
    </script>

and the controler Register.php methode ajax_call()

public function ajax_call(){

if (isset($_REQUEST['input']))
        {
        //  echo("hello");
        $input = $_REQUEST['input'];
        $this->load->model('Pro_model');
        $commune=$this->Pro_model->get_dropdown_commune($input);
        //print_r($commune);
        //$this->load->view('registerpro_view', $commune); 
       echo form_dropdown('commune', $commune, 'Adrar');
        }


}

and in the model side Pro_model.php

function get_dropdown_commune($input)
{
$this->db->from('ea_commune');
$this->db->where('id_wilaya', $input);
$this->db->order_by('id');
$result = $this->db->get();
$return = array();
if($result->num_rows() > 0) {

foreach($result->result_array() as $row) {
$return[$row['id']] = $row['label_commune'];
}
}

        return $return;

}