简体   繁体   中英

Codeigniter ajax send data to controller using ajax code

<script type="text/javascript">
    $(document).ready(function () {
        $("#select-dept").change(function () {
            var id = $("#select-dept").val();
            $.ajax({
                type: "POST",
                url: "<?=base_url()?>.index.php/sms/get_dept_employee",
                //url: baseurl + 'sms/get_dept_employee',
                data: "id",
                dataType = "json",
                cache: "false",
                success: function (emp_list) {
                    $("#dept-emp").html(emp_list);
                }
            });
        });
    });
</script>

I am unable to send view data to controller function In view their is select box with departmenr values from mysql database

<select class="select-dept" id="select-dept" name="select-dept">
    <option>Select Department</option>
    <?foreach ($departments as $dt):?>
        <option value="<?=$dt['id']?>">
            <?=$dt[ 'name']?>
        </option>
    <?endforeach;?>
</select>

i need to get refresh when user select department and that need to call controller function get_dept_employee And need to display datagrid of employee list

you need to send data option as object

try this

 .....
 url: "<?=base_url()?>.index.php/sms/get_dept_employee",
 data: {"id":id},
 dataType:"json",
 ....

and get the posted value as id in your controller..

$id=$this->input->post('id');
....
var id = $("#select-dept").val();     

 data:"id", //Here you are sending string as id

should be

     data:id, //No double quotes surrounded 

尝试:

data: {'id':$(this).val()},

i saw few errors

use data: {'id':id}, instead of data: "id",

use dataType:"json", instead of dataType="json",

use cache:false instead of cache: "false",

<script type="text/javascript">
    $(document).ready(function () {

        var base_url = "<?php echo $this->config->item('base_url'); ?>";

        $("#select-dept").change(function () {

            var id = $(this).val();
            $.ajax({
                type: "POST",
                url: base_url+"index.php/sms/get_dept_employee";
                data: {'id':id},
                dataType:"json",
                cache: false
                success: function (emp_list) {
                    $("#dept-emp").html(emp_list);
                }
            });
        });
    });
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM