how to pass data on ajax to codeigniter controller

Viewed 565

I have a select option. I want to pass the selected option value to my controller from ajax. But, I got the value is null when I'm trying to echo it from my controller (so I can see the value).

this is how I display my select option :

<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 :

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 :

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

I think there is a problem when I pass the data from ajax. I this the right command to pass the data?

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

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

Try with the change below, have used it a couple of times.

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