![]() |
CSRF token for AJAX call in attached javascript file - Printable Version +- CodeIgniter Forums (https://forum.codeigniter.com) +-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5) +--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24) +--- Thread: CSRF token for AJAX call in attached javascript file (/showthread.php?tid=91657) |
CSRF token for AJAX call in attached javascript file - xanabobana - 09-12-2024 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) 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! RE: CSRF token for AJAX call in attached javascript file - JanFromHamburg - 09-14-2024 maybe this helps? Kr Jan 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; } }, RE: CSRF token for AJAX call in attached javascript file - xanabobana - 09-20-2024 Thank you! I finally got a chance to try this and it worked. |