Search code examples
ajaxcodeignitercodeigniter-3

Ajax With Csrf Protection showing 403 forbidden in codeigniter 3.1.9


I am having issue while sending request to controller via ajax with csrf protection on. Its always gives an error as 403 forbidden. Facing this issue on localhost and on live server also. Using condeigniter 3.1.9

Following are my config values.

$config['csrf_protection'] = TRUE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = FALSE;
$config['csrf_exclude_uris'] = array();

Ajax Code as Follow

$.ajax({
    type:"POST",
    url:"http://localhost/Demo/products/getdata",
    dataType:'html',
    data:"char="+char,
    success: function(data){
        $('#proCatS').html(data);
    }
});

Please Help to solve this issue. Thanks !


Solution

  • You can get csrf_token_name and csrf_hash code and pass these parameter in POST

    var csfrData = {
        '<?php echo $this->security->get_csrf_token_name(); ?>': 
             '<?php echo $this->security->get_csrf_hash(); ?>'
    };
    
    $.ajax({
        type: "POST",
        url: "http://localhost/Demo/products/getdata",
        data: {
            char: char, 
            csrf_test_name: csfrData
        },
        success: function(data) {
            $('#proCatS').html(data);
        }
    });