PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label ajaxform. Show all posts
Showing posts with label ajaxform. Show all posts

Friday, March 18, 2022

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

 March 18, 2022     ajaxform, cakephp, cakephp-3.0, php     No comments   

Issue

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



Answered By - David A.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing