Welcome Guest, Not a member yet? Register   Sign In
CSRF token for AJAX call in attached javascript file
#1

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:

Code:
//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!
Reply


Messages In This Thread
CSRF token for AJAX call in attached javascript file - by xanabobana - 09-12-2024, 10:23 AM



Theme © iAndrew 2016 - Forum software by © MyBB