rjcode rjcode - 4 days ago 6
Ajax Question

Codeigniter CSRF protection with datatables ajax url

I am using codeigniter and we have enabled CSRF protection,

$config['csrf_protection'] = TRUE;


We have used :

`<input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">`


in the form submission and its working fine,

But my application also use DataTables to get server data with AJAX,

var handleDataTable = function () {
var table = $('#my_table').DataTable({
"ajax": {
"url" : baseURL + "user/core/data/"+report_id,
"dataType" : "json",
"type" : "POST", // ajax source
},
});
}


Obviously this will show "
The action you have requested is not allowed.
" message,

How can i pass csrf in Ajax retrieving data?

Answer

Pass it as a header in your Ajax function :

var handleDataTable = function () {

    var table = $('#my_table').DataTable({
      "ajax": {
          "url" : baseURL + "user/core/data/"+report_id,
          "dataType" : "json",
          "type" : "POST", // ajax source
          "headers": {
            'CSRFToken': TOKEN //replace by your name/value
          }
        },
});

If you have many Ajax requests, you should set a global header for all of them :

$.ajaxSetup( {
    headers: {
        'CSRFToken': TOKEN  //replace by your name/value
    }
});

Or send the name/value pair as part of the data :

$('#myTable').DataTable( {
    ajax: {
        url: '...',
        data: function ( d ) {
            d.csrfName = csrfValue;
        }
    }
} );

Source

Comments