user9746358
user9746358

Reputation:

403 error with ajax on CodeIgniter

I want to use Ajax (with the JQuery plugin Datatables) on my CodeIgniter application and when I put the address of the controller, I have a 403 error. I use the 3.1.8 version of Codeigniter. My code :

$('#Table').DataTable( {
    "processing": true,
    "serverSide": true,
    ajax: {
        url: '<?= base_url('myController/data');?>',
        "type": "POST"
    },
    "columns": [
        { "data": "col1" },
        { "data": "col2" },
        { "data": "col3" },
    ]
} );

I tried to put the $config['csrf_regenerate'] at false but nothing change

Upvotes: 0

Views: 634

Answers (3)

Karlo Kokkak
Karlo Kokkak

Reputation: 3714

You need a csrf token as well to be passed with your ajax data. Without it you'll get 403 error. Since, $config['csrf_regenerate'] is false in your config, you only need to get the token value once, and use it in all your requests.

Use the below functions to get the token name and get a value for it.

$this->security->get_csrf_token_name();
$this->security->get_csrf_hash();

In your controller method, you set the values of $data['csrf_token_name'] and $data['csrf_token_hash'] using the above methods to be used in the view code below.

$('#Table').DataTable( {
    "processing": true,
    "serverSide": true,
    ajax: {
        url: '<?= site_url('myController/data');?>',
        "type": "POST",
        data: { '<?php echo $csrf_token_name; ?>' : '<?php echo $csrf_token_hash; ?>' }
    },
    "columns": [
        { "data": "col1" },
        { "data": "col2" },
        { "data": "col3" },
    ]
} );

Upvotes: 1

BILAL MALIK
BILAL MALIK

Reputation: 141

"url": base_url + 'myController/data',

try this as your url, echo in myController to see if you are going to the url or not.

I hope you've permission to access that path.

Upvotes: 0

JohnR
JohnR

Reputation: 57

Your Url shoud look like :

url: "<?= base_url('myController/data');?>",

Upvotes: 0

Related Questions