0

I am submitting a form using ajax with enabling CSRF protection to true in config.php. First time, the form is submitting well but second time it's showing error "Forbidden. The Action you requested is not allowed. 403". How can I securely submit form using ajax by enabling CSRF protection to true. Below is the ajax function I am using.

$('#loginfrmbtn').on('click', function(){
  $(this).prop('disabled', true);
  var formdata=$('#loginfrm').serialize();
  $.ajax({
    type: 'POST',
    data: formdata,
    url: '<?php echo base_url('logincheck');?>',
    dataType: 'json',
    success: function(res){
      $('#loginfrmbtn').prop('disabled', false);
      console.log(res);
      
    }, error: function(jqXHR){
      console.log(jqXHR);
    }
  })
})
Abhishek
  • 149
  • 1
  • 1
  • 15

1 Answers1

0

Try to use the headers option of the jQuery ajax function (https://api.jquery.com/jquery.ajax/) to send the csrf token within each request like so:

$.ajax({
    ...
    headers:{
        'X-CSRF-TOKEN': $( 'input[id="csrf_tsecurity"]' ).val(),
    },
    ...
});

And the following codeigniter config:

public $CSRFTokenName  = 'csrf_tsecurity';
public $CSRFHeaderName = 'X-CSRF-TOKEN';
public $CSRFRegenerate = false;
  • I want the regenerate token to be true. – Abhishek Aug 03 '20 at 08:25
  • Than you need to update your csrf_tsecurity input field. i.e like here: https://stackoverflow.com/a/56380192/7952420 You can do this in your success/error/complete callbacks. – Martin Wilm Aug 03 '20 at 09:07