Dropdown population using jquery to get data from codeigniter controller

限于喜欢 提交于 2019-12-12 05:17:10

问题


I want to populate a dropdown using jquery and ajax.

my jquery call is

<script>
        $(document).ready(function(){
            $.ajax({           
                type: "GET",
                url: "<?=base_url()?>user/getstate/",                  //the script to call to get data          
                data:'',                        //you can insert url argumnets here to pass to api.php
                dataType: 'json',                //data format      
                success: function(data){    //on recieve of reply
                    $("#state").append('<option selected>State</option>');
                    for(i in data) 
                        $("#state").append("<option value=\""+data[i][0]+"\">"+data[i][1]+"</option>");
                } 

            });
        });
    </script>

the part that needs to be populated is

<select id="state" class="span2" style="height:30px" name="state" required>
</select>

the function in the controller is

public function getstate(){

        $this->load->model('usermodel');
        $data=$this->usermodel->getstate();
        echo json_encode($data);


}

the model from which the data is being fetched is

public function getstate(){
    $sql="SELECT * FROM statelist";
    $query=$this->db->query($sql);
    $result=$query->result_array();
    return $result;
}

the datas in statelist are

sid | statename

wb | West Bengal

ga | Goa

The problem i am facing is that when I load the page I get the dropdown with 2 elements as expected but in this form

State
undefined
undefined

Now i don't understand why am i getting "undefined" instead of the required or expected data like

State
West Bengal
Goa

A solution will really help me.


回答1:


Jquery turns your json into an object, so you need to referene it like:

data.i

not

data[i]

like you would with an array.

But im guessing that i is not your key. If you try and log data "console.log(data)" in success parameter, you should be able to see the correct key names.



来源:https://stackoverflow.com/questions/15852664/dropdown-population-using-jquery-to-get-data-from-codeigniter-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!