CodeIgniter Forums
How to fix error 403 when csrf enabled with ajax - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=31)
+--- Thread: How to fix error 403 when csrf enabled with ajax (/showthread.php?tid=78398)



How to fix error 403 when csrf enabled with ajax - onebuyu - 01-13-2021

Hi everyone, I'm struggling to retrieve data with ajax, I enabled csrf. When I use method: 'get' I get the data, but when I use post method did not work.



PHP Code:
//my route
$routes->post('view-category''Admin\Category::show_category');

//my controller
public function __construct(){
      helper('security');
}

public function 
show_category(){
      $output['csrf_token'] = csrf_token();
      $output['csrf_hash']   csrf_hash();
      echo json_encode($output);

Code:
// javascript
function view_category(){
      let url = 'view-category';
      let csrfName = '<?= csrf_token()?>';
    let csrfHash = '<?= csrf_hash() ?>';
      $.ajax({
           url: url,
           method: 'post',
           data: {csrfName: csrfHash },
           dataType: 'json',
           success: function(data)
           {
          alert("success");
           }
      })
}



RE: How to fix error 403 when csrf enabled with ajax - onebuyu - 01-13-2021

I solved it by adding angle blackets "[]"to the data key like this:
Code:
data: {[csrfName]: csrfHash },



RE: How to fix error 403 when csrf enabled with ajax - iRedds - 01-13-2021

The browser developer tool is your best friend

You cannot use a variable as an object property name when writing code like this.
 data: {csrfName: csrfHash }  

Use like this

let data = {}
data[csrfName] = csrfHash


and than

$.ajax({ .... data : data 

Or you can send the header in the request.

let csrfHeader = '<?=csrf_header() ?>'

$.ajax({ 
url : 'some-url',
beforeSend: function(request) {
  request.setRequestHeader(csrfHeader, csrfHash);
},
data : { key : value },
....

(01-13-2021, 02:52 PM)onebuyu Wrote: I solved it by adding angle blackets "[]"to the data key like this:
Code:
data: {[csrfName]: csrfHash },

Interesting. Thx. I didn't know anything about computed properties.