简体   繁体   English

如何将 ajax 上的数据传递给 codeigniter controller

[英]how to pass data on ajax to codeigniter controller

I have a select option.我有一个 select 选项。 I want to pass the selected option value to my controller from ajax.我想将选定的选项值从 ajax 传递给我的 controller。 But, I got the value is null when I'm trying to echo it from my controller (so I can see the value).但是,当我试图从我的 controller 回显它时,我得到的值是 null (所以我可以看到这个值)。

this is how I display my select option:这就是我显示 select 选项的方式:

<form class="form-horizontal" action="#">
    <select name="categories" onchange="ipilihCat()" id="categories" class="js-example-placeholder-single form-control" style="width: 200px;">
        <option value="">pilih category</option>
        <?php
        foreach ($cats as $cats) {
            echo '<option value="' . $cats['category'] . '">' . $cats['category'] . '</option>';
        }
        ?>
    </select>
</form>

here is the ajax code that I use:这是我使用的 ajax 代码:

function ipilihCat(){
var selected = $('#categories').val();

$('#target').DataTable({
    "processing": true,
    "serverSide": true,
    "order": [],
    "ajax": {
        "data": {
            'cats': selected
        },
        "dataType": 'json',
        "url": "<?= base_url('welcome/iselCats'); ?>",
        "type": "POST",
        "success": function(data) {
            console.log(data);
        }
    },
    "columnDefs": [{
        "target": [-1],
        "orderable": false
    }],
});
}

And in my controller, I check it like this:在我的 controller 中,我这样检查:

public function iselCats(){
   $cats = $this->input->post('cats');
   echo $cats;
}

I think there is a problem when I pass the data from ajax.我认为当我从 ajax 传递数据时有问题。 I this the right command to pass the data?我这是传递数据的正确命令吗?

"data": {
            'cats': selected
        },

Change the following line in your code更改代码中的以下行

$('#target').DataTable({

to

var table = $('#target').DataTable({

and add the following code并添加以下代码

$('#categories').on("change",function(){
    table.ajax.url( "<?= base_url('welcome/iselCats'); ?>?cats="+this.value ).load();
});

this will send the cats to your server and refresh the table and the rest of the filtering code will be handled serverside manually这会将猫发送到您的服务器并刷新表,过滤代码的 rest 将在服务器端手动处理

Try with the change below, have used it a couple of times.尝试以下更改,已使用过几次。

"url": "<? echo base_url('welcome/iselCats'); ?>",

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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