2

Need help,

I want to be able to send a form via ajax to a controller for processing while the crsf and security components are enabled in the App controller (cakephp 3.4). Will appreciate any help I can get. Thanks

medhybrid
  • 48
  • 6
  • I think those components just create hidden fields. Have you tried just including the hidden fields in your ajax request? I am not sure that will work, but its worth trying. – cnizzardini Jul 17 '17 at 05:27
  • try this answer [How to check CSRF token using AJAX and CakePHP 3](https://stackoverflow.com/questions/33994845/how-to-check-csrf-token-using-ajax-and-cakephp-3-when-user-is-not-logged-in/35238944#35238944) The CSRF token is available in cookie named csrfToken, so read that token in your javascript and set X-CSRF-Token header for your AJAX request. The CsrfCompoment will do the checking. – eclaude Jul 18 '17 at 09:48

1 Answers1

2

In order to send an ajax request you need to send the csrf token first through the head request as specified in the docs (link)

Cakephp 3.6+

This is an example with a jquery ajax call

$.ajax({
    url: '<?php echo $this->Url->build(['controller' => 'Foo', 'action' => 'bar'])?>',
    beforeSend: function(xhr){
        xhr.setRequestHeader('X-CSRF-Token', '<?php echo $this->request->getParam('_csrfToken') ?>'));
    }
});

Cakephp below 3.6

You need to create or use a cookie reader for javascript (like: js-cookie)

This is an example with a jquery ajax call and js-cookie:

$.ajax({
    url: '<?php echo $this->Url->build(['controller' => 'Foo', 'action' => 'bar'])?>',
    beforeSend: function(xhr){
        xhr.setRequestHeader('X-CSRF-Token', Cookies.get('csrfToken'));
    }
});

Edit: updated answer after cakephp 3.6 is released

David A.
  • 91
  • 4
  • I have now a similar issue in 3.7.3 which is not resolved by just sending the csrf token, I wonder if something has changed in the Middleware. https://stackoverflow.com/questions/54562777/cakephp-3-7-3-invalid-security-debug-token-with-ajax-request-400 – Sam Feb 07 '19 at 08:00