Reputation: 323
So I want to enable CSRF protection in my codeigniter app, but this means my js no longer works when its in an external file
function saveToDatabase(editableObj,field,id)
{
var pathArray = window.location.pathname.split( '/' );
var segment_3 = pathArray[3];
var save_data = {
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>',
'field':field,
'editedValue':editableObj.innerHTML,
'id':id
};
$.ajax({
url: segment_3+'/update',
type: 'POST',
data:save_data,
success: function(){
$(editableObj).addClass('bg-success');
}
});
}
I tested by copy pasting it into the view file, and it works perfectly fine. So the problem is that this line
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>',
wont work in an external file? Is there any way to get that working?
Upvotes: 3
Views: 1937
Reputation: 319
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.
Upvotes: 0
Reputation: 1082
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
};
Upvotes: 4