Search code examples
phpcakephpcakephp-3.0ajaxform

Sending form via ajax in cakephp 3.4 with crsf and security components enabled


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


Solution

  • 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