Using CSRF with AJAX Codeigniter Datatables

Using CSRF with AJAX Codeigniter Datatables

FedericoVFedericoV Posts: 35Questions: 9Answers: 0

First of all I have to say sorry for my poor english...I hope to explain my issue and find a solution thanks to this community.
The issue: I'm not able to pass regenerated CSRF token to AJAX Datatables in Codeigniter.
The first loading table works fine but I get error trying to perform any Datatables action...like searching data, reordering column and so on...
The server PHP code...in the last rows..is the following:

        $csrf_name = $this->security->get_csrf_token_name();
        $csrf_hash = $this->security->get_csrf_hash();  
        
        $json_data = array(
                    "draw"            => intval($this->input->post('draw')),  
                    "recordsTotal"    => intval($totalData),  
                    "recordsFiltered" => intval($totalFiltered), 
                    "data"            => $data  
                    );

        $json_data[$csrf_name] = $csrf_hash;    
        
        echo json_encode($json_data); 

As I wrote...the code works fine the first time...
Here you are the Javascript code:

```
//Ajax datatables
var table = $('#table').DataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"responsive": true,
"autoWidth": false, // Make Datatable really responsive
"order": [[ 0, "asc" ]], //Initial order for registration column.
"stateSave": true, // Save user state
"lengthMenu": [[15, 25, 50, -1], [15, 25, 50, "All"]],
"responsive": true,
"searchHighlight": true,

// Load data for the table's content from an Ajax source
"ajax": {
    "url": url + '/ajax_list',
    "dataType": "json",
    "type": "POST",
    "data": {"csrf_test_name": token_value},
    complete: function(response) {
       var data  = JSON.parse(response.responseText).data;

       $.ajaxSetup({
            data: CsrfSecret
        });
    },

},
"columns": [
              { "data": "cbtid" },
              { "data": "contributer" },
              { "data": "images" },
              { "data": "date" },
              { "data": "action" },
           ] , 
"createdRow": function ( row, data, index ) {
    $('td', row).eq(4).attr('data-id', data.cbtid);
},  
//Set column definition initialisation properties.
"columnDefs": [
{ 
    "targets": [ 4 ], //fifth column.
    "orderable": false, //set not orderable
    "searchable": false, //set not searchable
}],
dom: "Bfrtip",
buttons: [{
    extend: "copy",
    className: "btn-sm"
}, {
    extend: "csv",
    className: "btn-sm"
}, {
    extend: "excel",
    className: "btn-sm"
}, {
    extend: "pdf",
    className: "btn-sm"
}, {
    extend: "print",
    className: "btn-sm"
}],
"language": {
    "processing": "Loading. Please wait ..."
},

});

```

I'm trying to retrieve the csrf_name token value returned by the server to set the CSRF token for the next POST request, did several test using "complete" or "dataSrc" Datatables function but no way to read those variables to set the new token.
Thanks a lot for any help

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,550Questions: 1Answers: 10,476 Site admin
    Answer ✓

    Use ajax.data as a function. That way it will be able to get the latest token whenever it is called by DataTables. For example you might simply have the token stored in a variable and then do:

    ajax: {
       ...,
       data: function ( d ) {
         d.csrf_test_name = token;
       }
    }
    

    Allan

  • FedericoVFedericoV Posts: 35Questions: 9Answers: 0

    Thanks a lot allan; fixed the issue following your hint.

This discussion has been closed.