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

旧巷老猫 提交于 2019-12-11 05:59:23

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/45123481/sending-form-via-ajax-in-cakephp-3-4-with-crsf-and-security-components-enabled

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!