0

I'm working in Codeigniter 4 with CSRF protection enabled. I have an AJAX call in an attached js file, and I can't figure out how to generate the CSRF token. Previously, I have done it in php files with embedded js, but in the attached js file I can't run php.

In the attached js file I have:

//makes a tooltip with description of analysis (header)
    $('.tbl-header').each(function () {
        makeHeaderInfo($(this))
    })

function makeHeaderInfo(header) {
        var analysis = header.hasClass('seed') ? 'Seedling ' + header.text().toLowerCase() : 'Sapling ' + header.text().toLowerCase();
        var posturl = baseURL + "forest_regen/getAnalysisDetails";
        var data = {};
        data['analysis'] = analysis;
//This is what I would do in a php file...
//       var csrfName = '<?= csrf_token() ?>'; 
//       var csrfHash = '<?= csrf_hash() ?>';   
//       data[csrfName]=csrfHash;
        $.when($.ajax({type: "POST", url: posturl, data: data, dataType: 'json'})).done(function (result) {
            var description = (result.fldDescription == null) ? 'No description for this analysis yet' : result.fldDescription
            header.children('.header-info').attr('title', description)
                    .tooltip({
                        trigger: 'click hover',
                        placement: 'top',
                        container: 'body'
                    })
        })
    }
    ;

I tried defining the variables in the php file which has this js file attached, but I get "csrfName is not defined." I'm not sure how to pass the variables to the js file?

Is there a way to generate the csrfName and csrfHash in javascript or jquery? Or another way to accomplish this?

Thank you!

2 Answers 2

0

Maybe making a route to return the created crsf_token would work, or saving to the browser cache or server session would work too

like:

returnCSRF = async () => {
//function to make a POST call from ajax to a route in the server what return the csrf
}
const csrf = await returnCSRF()
Sign up to request clarification or add additional context in comments.

3 Comments

hm, wouldn't I need a CSRF token for that post call? Session is an interesting idea, I'll give that a try
In CodeIgniter 4, there are filter options. You can modify something, like CSRF in a route: ['filter' => 'csrf', 'except' => true] $routes->post('rota-sem-csrf', 'MeuController::rotaSemCSRF', ['filter' => 'csrf', 'except' => true]); It is not very safe, but it is one way to do it.
or goto Config/Filters.php and add 'csrf' => ['except' => ['Admin/index','Dashboard/index']], in the public $globals array This will exclude csrf checking for the pages Admin/index and Dashboard/index
0

I ended up using a hidden input field.

VIEW:

<input type="hidden" class="txt_csrfname" name="<?=csrf_token() ?>" value="<?=csrf_hash() ?>" />

JAVASCRIPT:

$('#functionInJSfile').DataTable({
'processing': true,
'serverSide': true,
'serverMethod': 'post',
'ajax': {
'url':"",
'data': function(data){
// CSRF Hash
var csrfName = $('.txt_csrfname').attr('name'); // CSRF Token name
var csrfHash = $('.txt_csrfname').val(); // CSRF hash

return {
data: data,
[csrfName]: csrfHash // CSRF Token
};
},
dataSrc: function(data){

// Update token hash
$('.txt_csrfname').val(data.token);

// Datatable data
return data.aaData;
}
},

1 Comment

you could also use CI's form_open()which automatically creates the hidden input, check Html Forms

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.