Barba Barba - 5 months ago 34
jQuery Question

Ajax post to CodeIgniter controller not working

I'm trying to post some data to CodeIgniter controller, but it only shows empty array. I'm also using DataTables. I'm not sure that I'm sending the data the right way. This is my code:

JS

$("#prw").on('click', function(e){
e.preventDefault();

var url = window.location.origin + "/nsl/preview";

$.ajax({
url: url,
data: $("input[type='checkbox']:checked").serialize()
}).done(function(data){
console.log("Response", data);
});
});


CONTROLLER

function preview() {
$post = $this->input->post();
return $post;
}


HTML

<table id="offers" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>...</th>
<th>...</th>
<th>...</th>
<th>...</th>
<th>...</th>
</tr>
</thead>
<tfoot>
<tr>
<th>...</th>
<th>...</th>
<th>...</th>
<th>...</th>
<th>...</th>
</tr>
</tfoot>
<tbody>
<?php foreach($data as $d): ?>
<tr>
<td><input type="checkbox" id="check" name="myCheckboxes[]" class="toggle" value="<?=$d->oid?>"></td>
<td><input type="text" id="rb" name="myText[]" class="toggle"></td>
<td><?=$d->fullname?></td>
<td><?=$d->published?></td>
<td><?=$d->expires?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<input type="submit" id="prw" class="btn btn-info" value="Preview">


Please I appreciate any help.

Answer

Certain things to check :-

  1. Inside the ajax call, mention type : 'post'

  2. On click function, try

    alert( $("input[type='checkbox']:checked").serialize() );

    and check whether you are getting the values as expected?

  3. Open Firebug, Click on Console, execute the click button, see what all values are present under POST tab of the URL inside the console.

  4. Inside the controller

    $post = $this->input->post('myCheckboxes'); print_r($post);