Getting CSRF token in external js file Getting CSRF token in external js file codeigniter codeigniter

Getting CSRF token in external js file


you can store this value to hidden input or any hidden element and then you can access it in external js file..

<input type ='hidden' name='what_you_want' id='whatever_you_like' value='<?php echo $this->security->get_csrf_token_name(); ?>'><input type ='hidden' name='what_you_want1' id='whatever_you_like1' value='<?php echo $this->security->get_csrf_hash(); ?>'>

and you can get it in js like this

var tmp = $('#whatever_you_like').val();var tmp1 = $('#whatever_you_like1').val();var save_data = {                     tmp: tmp1,                    'field':field,                    'editedValue':editableObj.innerHTML,                    'id':id                };


Define JS constant in header file like

var CSRF_NAME = '<?php echo $this->security->get_csrf_token_name(); ?>'

var CSRF_TOKEN = '<?php echo $this->security->get_csrf_hash(); ?>'

then just call CSRF_NAME or CSRF_TOKEN any where in external or inline JS.