0

I'm trying to apply server-side DataTables with Codeigniter, my controller code is:

 function get_logins() {

    $get_logins = $this->login_attempts_model->get_datatble();
    $data = array();
    foreach ($get_logins as $row){
        $subarray= array();
        $subarray[] = $row->id;
        $subarray[] = $row->ip_address;
        $subarray[] = $row->login_username;
        $subarray[] = $row->time;
        $subarray[] = $row->status;
        $subarray[] = '<button type="button" name="delete" id="'.$row->id.'"class="btn btn-danger">delete</button>';
        $data[]=$subarray;
    }
    $output = array(
        "draw" => $this->input->post(['draw']),
        "recordsTotal" => $this->login_attempts_model->get_all_data(),
        "recordsFiltered" => $this->login_attempts_model->count_filtered_data(),
        "data" => $data
    );
    echo json_encode($output);
}

and my view code including Jquery is:

<script type="text/javascript">

    $('#login_data').DataTable({
        "processing": true,
        "serverSide": true,
        "order": [],
        "ajax": {
            url: "<?= site_url('login_attempts/get_logins'); ?>",
            type: "POST",
            },
        "columnDefs": [
            {
                "targets": [4],
                "orderable": false,
            },
        ],
    });// also there are rest of other functions 
    </script>
<table id="login_data" class="table table-hover table-striped table-bordered results">
    <thead>
    <th>id</th>
    <th>IP Address</th>
    <th>Username </th>
    <th>Login Time</th>
    <th>actiona</th>
<th>Login Status</th>
</thead>
<tbody>
</tbody>
</table>

Everything goes fine and data fill up the table, but echo json_encode($output) is dumping data on the same page as JSON formatted data not only captured by the AJAX method.

the out put

Alessio
  • 3,404
  • 19
  • 35
  • 48
Eiaddar
  • 180
  • 1
  • 13

1 Answers1

0

dealing with this issue the solution was very simple: don't call method get_logins() from php controller add ajax method when document on load:

$(document).load(function () {
    $.ajax({
            url: 'login_attempts/get_logins',
            type: 'POST',
            dataType: 'json'
        });
});
this will resolve the problem of calling the method from controller and again from inside .dataTbles() method on ajax (it seems ambiguous but this is the only explanation I've figure it out)
Eiaddar
  • 180
  • 1
  • 13